# include # include "vector.h" # include "vector.c" extern void swap(vector &, int, int); int prtition(vector & v, int low, int high, int pivotIndex) { // move the pivot value to the bottom of the vector if (pivotIndex != low) swap(v, low, pivotIndex); pivotIndex = low; low++; // invarient: // v[i] for i less than low are less than or equal to pivot // v[i] for i greater than high are greater than pivot // move elements into place while (low <= high) { if (v[low] <= v[pivotIndex]) low++; else if (v[high] > v[pivotIndex]) high--; else swap(v, low, high); } // put pivot back between two groups if (high != pivotIndex) swap(v, pivotIndex, high); return high; } void qackSort(vector & v, int low, int high) { for (int ii = 0; ii < 10; ii++) cout << v[ii] << " "; cout << " & sorting " << low << " to " << high; // no need to sort a vector of zero or one elements if (low >= high) { cout << "\\\\\n"; return; } // select the pivot value int pivotIndex = (low + high) / 2; cout << " pivot index is " << pivotIndex << "\\\\\n"; // partition the vector pivotIndex = prtition(v, low, high, pivotIndex); for (ii = 0; ii < 10; ii++) cout << v[ii] << " "; cout << " & after partition \\\\\n"; // sort the two sub arrays if (low < pivotIndex) qackSort(v, low, pivotIndex - 1); if (pivotIndex < high) qackSort(v, pivotIndex + 1, high); } vector vals(10); //---------------------------------------------------------------------- main() { vals[0] = 8; vals[1] = 2; vals[2] = 6; vals[3] = 4; vals[4] = 0; vals[5] = 1; vals[6] = 3; vals[7] = 5; vals[8] = 7; vals[9] = 9; qackSort(vals, 0, 9); }