QUICKSORT METHOD public static void quick Sort int
QUICKSORT: METHOD public static void quick. Sort (int left, int right, int [ ] arr) { // use middle value of current partition to split it int i = left, j = right, p. Val = arr [(left + right) / 2]; do { // move index vals towards middle while values conform to partition while (arr [i] < p. Val) i++; while (arr [j] > p. Val) j--; // swap "out of partition" elements if (i <= j) { if (i < j) swap (i, j, arr); i++; j--; } // end if } while (i <= j); // invoke quicksort on resulting partitions if (left < j) quick. Sort (left, j, arr); if (i < right) quick. Sort (i, right, arr); } // end quick. Sort method QUICKSORT CISC-101 SPRING 2003 1
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 2
QUICKSORT: TRACE top level, p. Val: 21 1 st recursion, p. Val: 2 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 18 17 2 14 9 5 2 17 18 14 9 5 swap: 17 5 5 18 14 9 17 swap: 18 9 5 9 14 18 17 5 9 18 17 17 18 2 nd recursion, p. Val: 14 3 rd recursion, p. Val: 5 3 rd recursion, p. Val: 18 1 st recursion, p. Val: 43 2 nd recursion, p. Val: 21 swap: 18 2 swap: 18 17 21 91 43 66 24 21 24 43 66 91 21 24 66 91 2 nd recursion, p. Val: 66 DONE! QUICKSORT 2 5 9 14 17 18 21 CISC-101 SPRING 2003 24 43 swap: 91 24 3
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 QUICKSORT CISC-101 SPRING 2003 4
- Slides: 4