Sorting and Searching II
Sorting and Searching II
How do we merge?
80 38 95 84 66 10 79 44 26 87 96 12 43 81 3
2 80 38 95 84 66 10 79 26 87 96 12 43 81 3
Our goal is to choose the median element in the list as our pivot:
80 38 95 84 66 10 79 2 26 87 96 12 43 81 3
Move P1 to the right skipping elements which are less than the pivot.
Move P2 to the left skipping elements which are more than the pivot.
When we stop, swap P1 with the last element which is the pivot
8 1 4 9 6 3 5 2 7 0
8 1 4 9 0 3 5 2 7 6
P1 P2
8 1 4 9 0 3 5 2 7 6
P1 P2
2 1 4 9 0 3 5 8 7 6
P1 P2
2 1 4 9 0 3 5 8 7 6
P1 P2
2 1 4 5 0 3 9 8 7 6
P2 P1
2 1 4 5 0 3 6 8 7 9
Partition 1 Partition 2
At any time can you say anything about the
elements to the left of P1?
Elements to the left of P1 are less than or
equal to the pivot.
8 1 4 9 6 3 5 2 7 0
2 1 4 5 0 3 6 8 7 9
Partition 1 Partition 2
0 1 2 3 4 5 6 7 8 9
Partition 1 Sorted Partition 2 Sorted
Need to do any thing more? Merger is automatic
Pseudocode
Quicksort(A, left, right)
{ Find pivot;
Interchange pivot and A[right];
P1 = left; P2 = right – 1;
Partition(A, P1, P2, pivot); /*returns newP1*/
Interchange A[newP1] and A[right];
Quicksort(A, left, newP1-1);
Quicksort(A, newP1, right); }
Partition(A, P1, P2,pivot)
{
While (P1 P2)
{
While (A[P1] < pivot) increment P1;
While (A[P2] > pivot) decrement P2;
Swap A[P1] and A[P2];
increment P1; decrement P2;
}
newP1 = P1;
return(newP1);
}
Run time
Works by:
Putting items into correct bin (cell) of array,
based on key
BinSort example
K=5 list=(5,1,3,4,3,2,1,1,5,4,5)
Bins in array
key = 1 1,1,1
key = 2 2
Sorted list:
key = 3 3,3 1,1,1,2,3,3,4,4,5,5,5
key = 4 4,4
key = 5 5,5,5
BinSort example (2)
• K=5 list=(5,1,3,4,3,2,1,1,5,4,5)
Bins in array
key = 1 3
key = 2 1
Sorted list:
key = 3 2 1,1,1,2,3,3,4,4,5,5,5
key = 4 2
key = 5 3
BinSort Pseudocode
procedure BinSort (List L,K)
bins[1..K][]
// Each element of array bins is linked list.
// Could also BinSort with array of arrays.