QUICKSORT: METHOD
-
Upload
valtina-tony -
Category
Documents
-
view
29 -
download
0
description
Transcript of QUICKSORT: METHOD
QUICKSORT CISC-101 SPRING 2003 1
QUICKSORT: METHOD
public static void quickSort (int left, int right, int [ ] arr) {// use middle value of current partition to split itint i = left, j = right, pVal = arr [(left + right) / 2];do {
// move index vals towards middle while values conform to partitionwhile (arr [i] < pVal) i++;while (arr [j] > pVal) j--;// swap "out of partition" elementsif (i <= j) {
if (i < j) swap (i, j, arr);i++;j--;
} // end if} while (i <= j);// invoke quicksort on resulting partitionsif (left < j) quickSort (left, j, arr);if (i < right) quickSort (i, right, arr);
} // end quickSort method
QUICKSORT CISC-101 SPRING 2003 2
QUICKSORT: ILLUSTRATIONS
• next 2 pages show quicksort method in operation– first, listing array contents as they change
• underlining marks chosen partitioning value: 21• bolding marks values selected for swap: 24 18• bold vertical borders mark partitions of array: |
– second, graphical representation of recursive calls• red & green arrows mark recursion on left & right partitions
• dashed blue arrows mark base case, recursion ending
QUICKSORT CISC-101 SPRING 2003 3
QUICKSORT: TRACE
top level, pVal: 21 24 17 2 66 43 21 5 91 9 14 18 swap: 24 18
18 17 2 66 43 21 5 91 9 14 24 swap: 66 14
18 17 2 14 43 21 5 91 9 66 24 swap: 43 9
18 17 2 14 9 21 5 91 43 66 24 swap: 21 5
18 17 2 14 9 5 21 91 43 66 24
1st recursion, pVal: 2 18 17 2 14 9 5 swap: 18 2
2 17 18 14 9 5
2nd recursion, pVal: 14 17 18 14 9 5 swap: 17 5
5 18 14 9 17 swap: 18 9
5 9 14 18 17
3rd recursion, pVal: 5 5 9
3rd recursion, pVal: 18 18 17 swap: 18 17
17 18
1st recursion, pVal: 43 21 91 43 66 24 swap: 91 24
21 24 43 66 91
2nd recursion, pVal: 21 21 24
2nd recursion, pVal: 66 66 91
DONE! 2 5 9 14 17 18 21 24 43 66 91
QUICKSORT CISC-101 SPRING 2003 4
QUICKSORT: CALL TRACE
• Quick Sort execution tree (for the above example)
• RED: recurse on left partition• GREEN: recurse on right partition• BLUE: recursion ends
– test for (left < j) fails– or test for (i < right) fails