Data Structures & Algorithms Sorting
Recall Selection Sort Insertion Sort Merge Sort Now consider Bubble Sort Shell Sort Quick Sort Sorting
Keep passing through the array Exchange adjacent elements that are out of order Until array is sorted Bubble Sort void bubbleSort(Item a[], int l, int r) { for (int i = l; i < r; ++i) for (int j = r; j > i; --j) compExch(a[j-1], a[j]); }
Bubble Sort ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM * * * *
Property 6.3: BubbleSort uses about N 2 /2 comparisons and N 2 /2 exchanges on the average and in the worst case. Bubble Sort void bubbleSort(Item a[], int l, int r) { for (int i = l; i < r; ++i) for (int j = r; j > i; --j) compExch(a[j-1], a[j]); }
Make array h-sorted: h-sorted means the h sub-arrays are sorted (with sub-array i being elements in a[j] where j%h == i) Exchange distant elements that are out of order Decrease h until array is sorted (h = 1) Step sequence is not obvious, and there are many interactions – geometric best Knuth recommended s[i+1] = 3*s[i]+1 Shell Sort
Make array h-sorted for decreasing h: Shell Sort void shellSort(Item a[], int l, int r) {int h; for (h = 1; h <= (r-l)/9; h = 3*h+1); for ( ; h > 0; h/= 3) for (int i = l+h; i <= r; ++i) { int j = i; Item v = a[i]; while (j >= l+h && v < a[j-h]) { a[j] = a[j-h]; j -= h; } a[j] = v; }
Shell Sort ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM
Property 6.7: The result of h-sorting a file that is k-ordered is a file that is both h- and k- ordered. Property 6.8: ShellSort does less than N(h- 1)(k-1)/g comparisons to g-sort a file that is h- and k-ordered, provided that h and k are relatively prime Property 6.9: ShellSort does less than O(N3/2) comparisons for the Knuth sequence. ShellSort