Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures & Algorithms Sorting. Recall Selection Sort Insertion Sort Merge Sort Now consider Bubble Sort Shell Sort Quick Sort Sorting.

Similar presentations


Presentation on theme: "Data Structures & Algorithms Sorting. Recall Selection Sort Insertion Sort Merge Sort Now consider Bubble Sort Shell Sort Quick Sort Sorting."— Presentation transcript:

1 Data Structures & Algorithms Sorting

2 Recall Selection Sort Insertion Sort Merge Sort Now consider Bubble Sort Shell Sort Quick Sort Sorting

3 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]); }

4 Bubble Sort ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM * * * *

5 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]); } http://www.sorting-algorithms.com/bubble-sort

6 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

7 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; }

8 Shell Sort ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM ALGORITHM

9 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 http://www.sorting-algorithms.com/shell-sort


Download ppt "Data Structures & Algorithms Sorting. Recall Selection Sort Insertion Sort Merge Sort Now consider Bubble Sort Shell Sort Quick Sort Sorting."

Similar presentations


Ads by Google