40 likes | 187 Views
QUICKSORT: METHOD. public static void quickSort (int left, int right, int [ ] arr) { // use middle value of current partition to split it int i = left, j = right, pVal = arr [(left + right) / 2]; do { // move index vals towards middle while values conform to partition
E N D
QUICKSORT: METHOD public static void quickSort (int left, int right, int [ ] arr) { // use middle value of current partition to split it int i = left, j = right, pVal = arr [(left + right) / 2]; do { // move index vals towards middle while values conform to partition while (arr [i] < pVal) i++; while (arr [j] > pVal) 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) quickSort (left, j, arr); if (i < right) quickSort (i, right, arr); } // end quickSort method CISC-101 SPRING 2003
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: 2418 • 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 CISC-101 SPRING 2003
QUICKSORT: TRACE CISC-101 SPRING 2003
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 CISC-101 SPRING 2003