Compiled By: Dr. Mohammad Omar Alhawarat: Sorting
Compiled By: Dr. Mohammad Omar Alhawarat: Sorting
Comparison
Based Sorting
Sorting
4
Idea:
Repeatedlypass through the array
Swaps adjacent elements that are out of order
Worst-case: O(n2)
Array is in reverse order:
Average-case: O(n2)
We have to look at all possible initial data organizations.
Worst-case: O(n2)
Array is in reverse order:
Average-case: O(n2)
We have to look at all possible initial data organizations.
Idea:
Find the smallest element in the array
8 4 6 9 2 3 1 1 2 3 4 9 6 8
1 4 6 9 2 3 8 1 2 3 4 6 9 8
1 2 6 9 4 3 8 1 2 3 4 6 8 9
1 2 3 9 4 6 8 1 2 3 4 6 8 9
Selection Sort – Analysis
17
Worst-case: O(n2)
Array is in reverse order:
Average-case: O(n2)
We have to look at all possible initial data organizations.
Idea:
Isbased on “Merging” idea where two sorted lists are
combined in the right order.
Idea:
Repeatedly partition the data into two halves.
Only the element in the middle is sorted.
After (Log2N) repetitions then the data is sorted.
55, 70, 65, 68, 61, 75, 100, 93, 78, 98, 81,
84
The previous SPLIT operation placed pivot 75
so that all elements to the left were <= 75
and all elements to the right were >75.
75 is now placed appropriately
Need to sort sub-lists on either side of 75
55, 70, 65, 68, 61, 75, 100, 93, 78, 98, 81,
84 pivot 75
Quicksort Example
31
Need to sort
(independently):
55, 70, 65, 68, 61
100, 93, 78, 98, 81, 84
Quicksort performance
32
Quicksort performance:
O(nlogn) if the pivot results in sublists
of approximately the same size.
Non-comparing
sorts
Non-comparing sorts
46
What about sorts that don’t compare elements (or at least not much)?
e.g. Counting Sort
1. for i 0 to k - 1 do
2. C[i] 0
3. for j 0 to n - 1 do
4. C[A[j]]++
5. for i 1 to k - 1 do
6. C[i] += C[i - 1]
7. for j n - 1 down to 0 do
8. B[C[A[j]] - 1] A[j]
9. C[A[j]]- -
If each for loop has to do around n things (i.e. k =n), then counting sort
time = O(n).
Counting sort
47
Try to sort
12, 4, 2, 13, 6, 9, 5, 3, 8, 7
Radix Sort
48
1. n length of A
2. for i 0 to n - 1 do
3. insert A[i] into B[n * A[i] ]
4. for i 0 to n - 1 do
5. sort bucket B[i] with insertion sort
6. Concatenate the lists B[0] up to B[n - 1]
together in order
Consider tossing n balls into n buckets:
chances are good that the buckets stay
small.
Tricky aspects of Bucket Sort
52