exchange sort
exchange sort
A[0] A[1] A[ N 2] A[ N 1]
1
1/31/2024
Selection sort
Walk from left to right through the array.
On each step, select the element that goes
in the current location in sorted order and
In each iteration, selection sort put it there.
...
5
26 6 15 13 14 1 2 4 4 8 12 6 16 10 16 8 18 14
0 1 2 3 4 5 6 7 8 9 10 11
2 4 4 6 12 8 16 10 16 8 18 14
0 1 2 3 4 5 6 7 8 9 10 11
2 4 4 6 8 8 10 12 14 16 16 18
0 1 2 3 4 5 6 7 8 9 10 11
2
1/31/2024
10
Insertion sort
Walk from left to right through the array.
On each step, insert the element in the
current location in sorted order to its left.
... Figure 7.1: An example illustrating what Insertion Sort does when i=6 and
j=2 (top). The array before inserting, and (bottom) the insertion gap.
3
1/31/2024
Insertion Sort
Insertion sort (Java version)
8 16 4 8 12 6 4 10 16 2 18 14
public void insertionSort(Comparable[] a)
{
int N = a.length;
0 1 2 3 4 5 6 7 8 9 10 11
for (int i = 1; i < N; i++) {
int j = i;
while ((j > 0) &&
(less(a[j], a[j‐1]))) { 8 16 4 8 12 6 4 10 16 2 18 14
swap(a, j, j‐1);
j‐‐; 0 1 2 3 4 5 6 7 8 9 10 11
}
}
} 4 8 16 8 12 6 4 10 16 2 18 14
0 1 2 3 4 5 6 7 8 9 10 11
26 6 15 13 14 1 4 8 8 16 12 6 4 10 16 2 18 14
Invariants
0 1 2 3 4 5 6 7 8 9 10 11
On the kth iteration of the i loop:
}
} Therefore, it is generally better than the other
quadratic sorts if the elements are in random or
Running time is sensitive to input.
reverse order (not affected by the original order of
the array elements)
Best case: If the array is in ascending order (already sorted), insertion sort
makes N-1 comparisons and 0 swaps. If the array is nearly sorted, insertion sort The insertion sort is particularly appropriate for
makes a linear number of comparisons and swaps.
small arrays that are nearly sorted
Worst case: If the array is in descending order, insertion sort makes ~N2/2
comparisons and ~N2/2 swaps.
Average case: If the array is in random order, insertion sort makes ~N2/4
comparisons and ~N2/4 swaps on average.
4
1/31/2024