Presentation is loading. Please wait.

Presentation is loading. Please wait.

QUICKSORT Quicksort is a sort-in-place algorithm that uses “divide-and-conquer”. First, partition the array into two subarrays A and B such that all in.

Similar presentations


Presentation on theme: "QUICKSORT Quicksort is a sort-in-place algorithm that uses “divide-and-conquer”. First, partition the array into two subarrays A and B such that all in."— Presentation transcript:

1 QUICKSORT Quicksort is a sort-in-place algorithm that uses “divide-and-conquer”. First, partition the array into two subarrays A and B such that all in A <= all in B. Then quicksort A, and quicksort B.

2 Quicksort Code void quicksort(int p, int r) { if(p >= r) return; q = partition(p,r); quicksort(p, q-1); quicksort(q+1, r); }

3 Partitioning in Quicksort int partition(int p, int r) { for(x = A[p], i = p+1, j = r; ; ) { while( j > p && A[j] >= x) --j; while( i = j) { t = A[p]; A[p] = A[j]; A[j] = t; return j; } t = A[i]; A[i] = A[j]; A[j] = t; }}

4 Running Time of Quicksort Let quicksort(1,n) take T(n) time. Then “q = partition(p,r)” takes O(n) time, “quicksort(p, q-1)” takes about T(n/2) time, “quicksort(q+1, r)” takes about T(n/2) time. Thus T(n) = 2 * T(n/2) + O(n) The above recursive equation has a solution T(n) = O(n lg(n) ).

5 Improvements to Quicksort When the subarray A[p].. A[r] is small, say r – p < SMALL, the subarray can be sorted using insertionsort() or another O(n 2 ) algorithm. This saves on the number of recursive calls to quicksort.

6 Improvements to Quicksort void quicksort(int p, int r) { if(r – p < SMALL) { insertionsort(p, r); return; } q = partition(p,r); quicksort(p, q-1); quicksort(q+1, r); }


Download ppt "QUICKSORT Quicksort is a sort-in-place algorithm that uses “divide-and-conquer”. First, partition the array into two subarrays A and B such that all in."

Similar presentations


Ads by Google