1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class QuickSort { public: void sortArray(vector<int>& nums) { shuffle(nums); sort(nums, 0, nums.size() -1); }
void sort(vecotr<int>& nums, int lo, int hi) { if (lo >= hi) return ; int p = partition(nums, lo, hi); sort(nums, lo, p-1); sort(nums, p+1, hi); }
int partition(vector<int>& nums, int lo, int hi) { int pivot = nums[lo]; int i = lo + 1, j = hi; while (i <= j) { while (i < hi && nums[i] <= pivot) i++; while (j > lo && nums[j] < pivot>) j--; if (i >= j) break; swap(nums, i, j); } swap(nums, lo, j); return j; } void swap(vector<int>& nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }
void shuffle(vector<int>& nums) { int hi = nums.size() - 1; for (int i=0; i < nums.size() - 1; i++) { int randint = rand()% hi; swap(nums, i, randint); } }
}
|