#include <iostream>
#include <assert.h>
using namespace std;
int Partition(int *arr, int low, int high) {
if (low > high) {
assert(0);
}
if (low == high) {
return low;
}
int pivotkey = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivotkey) {
--high;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivotkey) {
++low;
}
arr[high] = arr[low];
}
arr[low] = pivotkey;
return low;
}
void Qsort(int *arr, int low, int high) {
if (arr == nullptr) { //未检验low和high合法性(只需要在这里检验一次就好)
assert(0);
}
if (low >= high) {
return;
}
int mid = Partition(arr, low, high);
Qsort(arr, low, mid-1);
Qsort(arr, mid+1, high);
}
void print_arr(int *arr, int len) {
for (int i = 0; i < len; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {49,38,65,97,76,13,27,49};
Qsort(arr, 0, 7);
print_arr(arr, 8);
system("pause");
return 0;
}
快速排序算法
最新推荐文章于 2022-08-23 11:38:17 发布