快速排序
int partition_(vector<int>& nums, int left, int right) {
int key = nums[left];
int st = left, ed = right;
while(st < ed) {
while(nums[ed] > key) ed--;
if (st < ed) swap(nums[st++], nums[ed]);
while(nums[st] < key) st++;
if (st < ed) swap(nums[ed--], nums[st]);
}
nums[st] = key;
return st;
}
void quickSort(vector<int>& nums, int left, int right) {
if (left < right) {
int pivot = partition_(nums, left, right);
quickSort(nums, left, pivot-1);
quickSort(nums, pivot+1, right);
}
return;
}
归并排序
void mergeArr(vector<int>& nums, int left, int mid, int right, vector<int>& tmp) {
int i = left, j = mid + 1;
int n = mid, m = right;
int k = 0;
while (i <= n && j <= m) {
if (nums[i] < nums[j]) tmp[k++] = nums[i++];
else tmp[k++] = nums[j++];
}
while (i <= n) tmp[k++] = nums[i++];
while (j <= m) tmp[k++] = nums[j++];
for (i=0; i<k; ++i) nums[left++] = tmp[i];
return;
}
void mergeSort(vector<int>& nums, int left, int right, vector<int>& tmp) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid, tmp);
mergeSort(nums, mid+1, right, tmp);
mergeArr(nums, left, mid, right, tmp);
}
return;
}
堆排序
void adjust_(vector<int>& nums, int len, int index) {
int left = index * 2 + 1;
int right = index * 2 + 2;
int minIndex = index;
if (left < len && nums[minIndex] < nums[left]) minIndex = left;
if (right < len && nums[minIndex] < nums[right]) minIndex = right;
if (index != minIndex) {
swap(nums[index], nums[minIndex]);
adjust_(nums, len, minIndex);
}
return;
}
void heapSort_(vector<int>& nums, int len) {
for (int i=len/2-1; i>=0; --i) {
adjust_(nums, len, i);
}
for (int i=len-1; i>=1; --i) {
swap(nums[i], nums[0]);
adjust_(nums, i, 0);
}
return;
}