The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998 The.Algorithm.Design.Manual.Springer-Verlag.1998

18.04.2013 Views

Lecture 5 - quicksort Thus we can sort the elements to the left of the pivot and the right of the pivot independently! This gives us a recursive sorting algorithm, since we can use the partitioning approach to sort each subproblem. Listen To Part 5-5 Listen To Part 5-6 Sort(A) Quicksort(A, low, high) Partition(A,low,high) Quicksort(A,1,n) if (low < high) pivot = A[low] leftwall = low file:///E|/LEC/LECTUR17/NODE5.HTM (3 of 10) [19/1/2003 1:34:35] Quicksort Animations Pseudocode pivot-location = Partition(A,low,high) Quicksort(A,low, pivot-location - 1) Quicksort(A, pivot-location+1, high)

Lecture 5 - quicksort Listen To Part 5-7 for i = low+1 to high swap(A[low],A[leftwall]) if (A[i] < pivot) then Best Case for Quicksort leftwall = leftwall+1 swap(A[i],A[leftwall]) Since each element ultimately ends up in the correct position, the algorithm correctly sorts. But how long does it take? The best case for divide-and-conquer algorithms comes when we split the input as evenly as possible. Thus in the best case, each subproblem is of size n/2. The partition step on each subproblem is linear in its size. Thus the total effort in partitioning the problems of size is O(n). The recursion tree for the best case looks like this: The total partitioning on each level is O(n), and it take levels of perfect partitions to get to single element subproblems. When we are down to single elements, the problems are sorted. Thus the total time in the best case is . Listen To Part 5-8 file:///E|/LEC/LECTUR17/NODE5.HTM (4 of 10) [19/1/2003 1:34:35]

Lecture 5 - quicksort<br />

Thus we can sort the elements to the left of the pivot and the right of the pivot independently!<br />

This gives us a recursive sorting algorithm, since we can use the partitioning approach to sort each subproblem.<br />

Listen To Part 5-5<br />

Listen To Part 5-6<br />

Sort(A)<br />

Quicksort(A, low, high)<br />

Partition(A,low,high)<br />

Quicksort(A,1,n)<br />

if (low < high)<br />

pivot = A[low]<br />

leftwall = low<br />

file:///E|/LEC/LECTUR17/NODE5.HTM (3 of 10) [19/1/2003 1:34:35]<br />

Quicksort Animations<br />

Pseudocode<br />

pivot-location = Partition(A,low,high)<br />

Quicksort(A,low, pivot-location - 1)<br />

Quicksort(A, pivot-location+1, high)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!