voidQuickSort(vector<int>& nums, int left, int right){ if(left < right){ int pos = Random_Partition(nums, left, right); QuickSort(nums, left, pos - 1); QuickSort(nums, pos + 1, right); } }
intPartition(vector<int>& nums, int left, int right){ int temp = nums[left]; while(left < right){ while(left < right && nums[right] >= temp) right --; nums[left] = nums[right]; while(left < right && nums[left] <= temp) left ++; nums[right] = nums[left]; } nums[left] = temp; return left; } // 更快版本的Partition intPartition2(vector<int>& a, int l, int r){ int x = a[r], i = l - 1; for (int j = l; j < r; ++j) { if (a[j] < x) { swap(a[++i], a[j]); } } swap(a[i + 1], a[r]); return i + 1; } // 优化,随机取 temp //int Random_Partition(vector<int>& nums, int left, int right) { // int i = rand() % (right - left + 1) + left; // 随机选一个作为我们的主元 // swap(nums[left], nums[i]); // return Partition(nums, left, right); //} };
归并排序
C++
voidmerge_sort(vector<int> a, int l, int r){ if(l < r){ int mid = (l + r) / 2;//从中间截开 merge_sort(a, l, mid);//把左边沿中间截开 merge_sort(a, mid + 1, r);//把右边沿中间截开 merge(a, l, r, mid);//合并 } }
voidmerge(vector<int> a, int l, int r, int mid){ vector<int> s();//一个新数组用来存储排序好的数组 int i = l, j = mid + 1;//两个变量分别指向左边和右边两组数的第一个数 while (i <= mid && j <= r) { if (a[i] < a[j]) s.push_back(a[i++]); else s.push_back(a[j++]); } while (i <= mid) s.push_back(a[i++]);//当一组数已经全部排进去之后,再将另外一组数的全部数字都排进去 while (j <= r) s.push_back(a[j++]); a.assign(s.begin(), s.end()); }