quicksort - welcome · quicksort uses divide-and-conquer strategy. partitions a list into smaller...

33
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Quicksort Quicksort Uses divide Uses divide - - and and - - conquer strategy. conquer strategy. Partitions a list into smaller and smaller Partitions a list into smaller and smaller sublists sublists about a value called the about a value called the pivot pivot . . The algorithm locates the pivot in its final The algorithm locates the pivot in its final position in such a way that every value to position in such a way that every value to the left of the pivot is the left of the pivot is pivot and every pivot and every value to the right of the pivot is value to the right of the pivot is pivot. pivot. Unlike mergesort, quicksort is an Unlike mergesort, quicksort is an in in - - place place sorting algorithm and requires no extra sorting algorithm and requires no extra storage space. storage space.

Upload: others

Post on 15-Sep-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

QuicksortQuicksortUses divideUses divide--andand--conquer strategy.conquer strategy.Partitions a list into smaller and smaller Partitions a list into smaller and smaller sublistssublists about a value called the about a value called the pivotpivot..The algorithm locates the pivot in its final The algorithm locates the pivot in its final position in such a way that every value to position in such a way that every value to the left of the pivot is the left of the pivot is ≤≤ pivot and every pivot and every value to the right of the pivot is value to the right of the pivot is ≥≥ pivot.pivot.Unlike mergesort, quicksort is an Unlike mergesort, quicksort is an inin--placeplacesorting algorithm and requires no extra sorting algorithm and requires no extra storage space.storage space.

Page 2: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (1)Partitioning a List (1)Choose as pivot the element at indexChoose as pivot the element at indexmid = (first + last)/2. The algorithm mid = (first + last)/2. The algorithm separates the elements of separates the elements of arrarr into two into two sublistssublists, , SSll and and SShh. . SublistSublist SSll is the lower is the lower sublistsublist and contains the elements and contains the elements ≤≤ pivot. pivot. The higher The higher sublistsublist, , SShh, contains the , contains the elements elements ≥≥ pivot.pivot.

// pivot = arr[mid] where mid = (last + first)/2mid = (10 + 0)/5 = 5pivot = arr[5] = 500;

Page 3: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (2)Partitioning a List (2)Exchange Exchange arr[firstarr[first] and ] and arr[midarr[mid] and set ] and set up a scan of the list with index range up a scan of the list with index range [first+1, last). The index [first+1, last). The index scanUpscanUp starts at starts at position first+1 and moves up the list, position first+1 and moves up the list, identifying the elements in identifying the elements in sublistsublist SSll. The . The index index scanDownscanDown starts at position last starts at position last --1 1 and moves down the list, identifying and moves down the list, identifying elements in elements in sublistsublist SShh..

Page 4: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (3)Partitioning a List (3)

The scanning process begins with index The scanning process begins with index scanUpscanUp and looks for the first element that and looks for the first element that is is ≥≥ pivot. Such an element will ultimately pivot. Such an element will ultimately belong in the upper belong in the upper sublistsublist SShh..Index Index scanDownscanDown moves down the list moves down the list looking for an element that is looking for an element that is ≤≤ pivot. pivot. The element will ultimately belong in the The element will ultimately belong in the lower lower sublistsublist SSll..

Page 5: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (4)Partitioning a List (4)The pair of elements, referenced byThe pair of elements, referenced byscanUpscanUp and and scanDownscanDown are in the wrong are in the wrong sublistssublists; ; arr[scanUparr[scanUp] ] ≥≥ pivot and pivot and arr[scanDownarr[scanDown] ] ≤≤ pivot. Exchange the pivot. Exchange the elements at the two positions and then elements at the two positions and then update the two indices so that the scan update the two indices so that the scan for misplaced elements can resume. for misplaced elements can resume.

// exchange elements to place them in proper subliststemp = arr[scanUp];arr[scanUp] = arr[scanDown];arr[scanDown] = temp;scanUp++; // set scanUp at next element up scanDown--; // set scanDown at next element down

Page 6: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (5)Partitioning a List (5)

Page 7: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (6)Partitioning a List (6)

The two scans with indices The two scans with indices scanUpscanUp and and scanDownscanDown work in tandem and locate the work in tandem and locate the next pair of elements that must be next pair of elements that must be repositioned to form the lower and upper repositioned to form the lower and upper sublistssublists. In the process, the two indices . In the process, the two indices move toward each other until they either move toward each other until they either land at the same position or pass one land at the same position or pass one another (another (scanDownscanDown ≤≤ scanUpscanUp).).

Page 8: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (7)Partitioning a List (7)Resume scanning up the list. scanUp halts at elementarr[4] = 550 ≥ 500. scanDown halts at arr[7] = 350 ≤ 500.Elements arr[4] and arr[7] are in the wrong sublists. Exchangethe elements and update the indices to positions 5 and 6.

Page 9: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (8)Partitioning a List (8)scanUp moves up the list, halting at position 5 (arr[5] = 800) and scanDown moves down the list, halting at position 6 (arr[6]=400). An exchange of elements and updates to the indices leave scanUp at position 6 and scanDown at position 5.

Page 10: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Partitioning a List (9)Partitioning a List (9)The partition process terminates when The partition process terminates when scanDownscanDown ≤≤ scanUpscanUp..The index The index scanDownscanDown is the index for the is the index for the pivot in the array.pivot in the array.Exchange arr[0] and Exchange arr[0] and arr[scanDownarr[scanDown] to ] to correctly position the pivot in the list. correctly position the pivot in the list.

Page 11: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student QuestionStudent Question

The pivot element is placed at arr[0] The pivot element is placed at arr[0] during the partitioning process.during the partitioning process.Why not select arr[0] as the pivot element Why not select arr[0] as the pivot element initially and save the step of moving it initially and save the step of moving it down from down from arr[midarr[mid]?]?

Page 12: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Quicksort Recursive DescentQuicksort Recursive Descent

Let the variable Let the variable pivotLocpivotLoc denote the index denote the index of the pivot. Recursive steps continue the of the pivot. Recursive steps continue the partitioning process on partitioning process on SSll with index range with index range [first, [first, pivotLocpivotLoc) and ) and SShh with index range with index range [pivotLoc+1, last).[pivotLoc+1, last).

Page 13: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Quicksort Recursive DescentQuicksort Recursive Descent(continued)(continued)

Sublist Sl: {400, 150, 300, 450, 350} with index range [0, 5). Then set mid = (0 + 5)/2 = 2 and pivot = arr[2] = 300

1-elementsublist

Further processing required for {400, 450, 350}

Page 14: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Quicksort Recursive DescentQuicksort Recursive Descent(continued)(continued)

Sublist Sh: {800, 550, 650, 900} with index range [6, 10)mid = (6 + 10)/2 = 8pivot = arr[8] = 650

1-elementsublist

Further processing required for {800, 900}

Page 15: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Quicksort Recursive DescentQuicksort Recursive Descent(continued)(continued)

Page 16: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Quicksort Recursive DescentQuicksort Recursive Descent(concluded)(concluded)

Page 17: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

pivotIndexpivotIndex()()

The methodThe methodpublic static <T extends Comparable<? super T>>public static <T extends Comparable<? super T>>intint pivotIndex(TpivotIndex(T[] [] arrarr, , intint first, first, intint last)last)

takes array arr and index range [first,last) and returns the index of the pivot after partitioning the range.

Page 18: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

pivotIndexpivotIndex() (continued)() (continued)

public static <T extends Comparable<? super T>>int pivotIndex(T[] arr, int first, int last) {

// index for the midpoint of (first, last) and// the indices that scan the index range in tandemint mid, scanUp, scanDown;// pivot value and object used for exchangesT pivot, temp;if (first == last) // empty sublist

return last;else if (first == last-1) // 1-element sublist

return first;else {

mid = (last + first)/2;pivot = arr[mid];

Page 19: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

pivotIndexpivotIndex() (continued)() (continued)// exchange the pivot and the low end of// the range and initialize the indices// scanUp and scanDownarr[mid] = arr[first];arr[first] = pivot;scanUp = first + 1;scanDown = last - 1;// manage the indices to locate elements// that are in the wrong sublist; stop when// scanDown <= scanUpfor(;;) {

// move up the lower sublist; continue// so long as scanUp is less than or// equal to scanDown and the array// value is less than pivotwhile (scanUp <= scanDown &&arr[scanUp].compareTo(pivot) < 0) scanUp++;

Page 20: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

pivotIndexpivotIndex() (continued)() (continued)

// move down the upper sublist so long// as the array value is greater// than the pivotwhile (pivot.compareTo(arr[scanDown]) < 0)

scanDown--;// if indices are not in their sublists,// partition completeif (scanUp >= scanDown)

break;// indices are still in their sublists// and identify two elements in wrong// sublists; exchangetemp = arr[scanUp];arr[scanUp] = arr[scanDown];arr[scanDown] = temp;

Page 21: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

pivotIndexpivotIndex() (concluded)() (concluded)

scanUp++;scanDown--;

}

// copy pivot to index (scanDown) that// partitions sublists and return scanDownarr[first] = arr[scanDown];arr[scanDown] = pivot;return scanDown;

}}

Page 22: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

quicksortquicksort()()

// sort arr using quicksortpublic static <T extends Comparable<? super T>>void quicksort(T[] arr){

qsort(arr, 0, arr.length);}

quicksortquicksort() takes an array () takes an array arrarr of generic of generic type as its argument and sorts the array type as its argument and sorts the array by calling the private method by calling the private method qsortqsort() with () with the index range [0, the index range [0, arr.lengtharr.length).).

Page 23: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

qsortqsort()()The method The method qsortqsort() implements the () implements the recursive quicksort algorithm.recursive quicksort algorithm.Recursively partition the elements in the Recursively partition the elements in the index range into smaller and smaller index range into smaller and smaller sublistssublists, terminating when the size of a list , terminating when the size of a list is 0 or 1.is 0 or 1.For efficiency, handle a list of size 2 by For efficiency, handle a list of size 2 by simply comparing the elements and simply comparing the elements and making an exchange if necessary. making an exchange if necessary.

Page 24: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

qsortqsort() (continued)() (continued)

For larger lists, call For larger lists, call pivotIndexpivotIndex() to reorder () to reorder the elements and determine the index, the elements and determine the index, pivotLocpivotLoc, for the pivot. Make two calls to , for the pivot. Make two calls to qsortqsort(). The first call uses the arguments (). The first call uses the arguments firstfirst and and pivotLocpivotLoc to specify the to specify the index range for the lower index range for the lower sublistsublist. The . The second call uses the arguments second call uses the arguments pivotLoc+1pivotLoc+1 and and lastlast to specify the to specify the index range for the upper index range for the upper sublistsublist. .

Page 25: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

qsortqsort() (continued)() (continued)

private static <T extends Comparable<? super T>>void qsort(T[] arr, int first, int last) {

// index of the pivotint pivotLoc;// temp used for an exchange in a 2-element sublistT temp;// if the range has 0 or 1 element, returnif (last - first <= 1)

return;

// if sublist has two elements, compare arr[first]// and arr[last-1] and exchange if necessaryelse if (last - first == 2){

Page 26: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

qsortqsort() (concluded)() (concluded)

if (arr[last-1].compareTo(arr[first]) < 0){temp = arr[last-1];arr[last-1] = arr[first];arr[first] = temp;

}return;

}else { // general case

pivotLoc = pivotIndex(arr, first, last);// make the recursive call for left partitionqsort(arr, first, pivotLoc);// make the recursive call for right partitionqsort(arr, pivotLoc +1, last);

}}

Page 27: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Running Time of QuicksortRunning Time of QuicksortThe average case running time isThe average case running time isO(nO(n loglog22n).n).The best case occurs when the array is The best case occurs when the array is already sorted.already sorted.

Page 28: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Running Time of QuicksortRunning Time of Quicksort(continued)(continued)

Quicksort is efficient even when the array Quicksort is efficient even when the array is in descending order.is in descending order.

Page 29: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Running Time of QuicksortRunning Time of Quicksort(concluded)(concluded)

The worstThe worst--case occurs when the pivot case occurs when the pivot consistently is the largest or smallest consistently is the largest or smallest element in its element in its sublistsublist. In this case, the . In this case, the running time is O(nrunning time is O(n22). This case is highly ). This case is highly unlikely to occur.unlikely to occur.

Page 30: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Comparison of Sorting Comparison of Sorting AlgorithmsAlgorithms

An An inversioninversion in an array, in an array, arrarr, is an ordered , is an ordered pair (pair (arr[iarr[i], ], arr[jarr[j]), i < j, where ]), i < j, where arr[iarr[i] > ] > arr[jarr[j]. When sorting in ascending order, ]. When sorting in ascending order, arr[iarr[i] and ] and arr[jarr[j] are out of order. ] are out of order. To sort in better than quadratic running To sort in better than quadratic running time, a sorting algorithm must compare time, a sorting algorithm must compare and exchange nonand exchange non--adjacent elements and adjacent elements and remove more than one inversion with each remove more than one inversion with each comparison.comparison.

Page 31: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

ComparsionComparsion of Sorting of Sorting Algorithms (concluded)Algorithms (concluded)

The O(nThe O(n22) sorting algorithms such as ) sorting algorithms such as selection and insertion sort generally selection and insertion sort generally remove one inversion with each iteration.remove one inversion with each iteration.The The O(nO(n loglog22n) sorting algorithms such as n) sorting algorithms such as quicksort and merge sort, compare quicksort and merge sort, compare nonadjacent elements and generally nonadjacent elements and generally remove more than one inversion with each remove more than one inversion with each iteration.iteration.

Page 32: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student QuestionStudent Question

Since Since QuicksortQuicksort is is O(nO(n loglog22n) and, unlike n) and, unlike mergesortmergesort, requires no auxiliary storage , requires no auxiliary storage why isnwhy isn’’t it used all the time for sorting? t it used all the time for sorting? Why should we waste our time studying Why should we waste our time studying any other sorting algorithms?any other sorting algorithms?

Page 33: quicksort - Welcome · Quicksort Uses divide-and-conquer strategy. Partitions a list into smaller and smaller sublists about a value called the pivot. The algorithm locates the pivot

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Student QuestionStudent Question

If recursion is If recursion is ““expensiveexpensive”” to implement, to implement, why not use a why not use a nonrecursivenonrecursive sort, such as sort, such as insertion sort, when the partitions become insertion sort, when the partitions become small enough?small enough?