Quick Sort - a recursive divide and conquer algorithm 10 8 20 16 Created by: Marifel C. Toledo 19 8 1 10 16 19 20 Did you know? Why it is the best? In most cases Quick Widely used as the Sort Sort Is the best function of many comparison sorting Less Memory algorithm. programming Fast languages. 2 1-PIVOT Steps 2-PARTITION “pivot” is the arbitrary element in the collection • • Rearrange the array elements in such a way that the all values lesser than the pivot Selection of the proper pivot will improve should come before the pivot and all the • Pick a Pivot – (random or median) the efficiency of the algorithm. values greater than the pivot should come Median of three partition is the most after it. popular method in choosing a pivot. It uses pivot as the median of the left most, right • into This 2 method is called partitioning the • Partition elements sections: most, or the middle element of the array. the end of the partition function, -elements<to pivotAt(left) list/array. the pivot element will be placed at its -elements>tosorted pivotposition. (right) • 1 2 3 • • Recursively Quick Sort the two halves 3-RECURSION down until sorted – (down to 1 element) Do the above process recursively to all the sub-arrays and sort the 3 elements. Key to Quick Sort’s Efficiency 1. Properly pick the Pivot 2. Quick Sort works best on UNSORTED lists or arrays. 4 EYES EYES HERE! HERE! EYES HERE! TEST CASE: Input data: 41 25 25 25 25 41 25 25 25 41 62 SAMPLE PROGRAM 41>13? 98>62? 25>13? 62>41? 41>98? j-41>62? i = 41>25? Pivot j-i++ Pivot =j j = i 98 25 13 41 13 41 62 41 62 62 62 41 62 i Pivot 13 62 13 13 41 1398 41 13 13 13 13 13 j 98 25 62 62 62 41 25 62 25 41 62 41 6213 98 98 98 25 98 98 98 98 98 j j ijj iii i j j i= jjj than i 98 Sorted Pivot 25data: Numbers lessii than Numbers greater TRUE pivot or equal to pivot TRUE FALSE FALSE TRUE TRUE 62 98 41 13 25 13 25 41 Pivot = 41 Pivot = 41 The illustration shows how quicksort works. 98 62