C++非递归的快速排序
时间: 2023-11-30 15:42:41 浏览: 75
以下是C++非递归的快速排序的实现:
```cpp
#include <iostream>
#include <stack>
using namespace std;
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
void quickSort(int arr[], int low, int high) {
stack<int> stk;
stk.push(low);
stk.push(high);
while (!stk.empty()) {
int h = stk.top();
stk.pop();
int l = stk.top();
stk.pop();
int pivot = arr[(l + h) / 2];
int i = l - 1;
int j = h + 1;
while (true) {
do {
i++;
} while (arr[i] < pivot);
do {
j--;
} while (arr[j] > pivot);
if (i >= j) {
break;
}
swap(arr[i], arr[j]);
}
if (l < j) {
stk.push(l);
stk.push(j);
}
if (j + 1 < h) {
stk.push(j + 1);
stk.push(h);
}
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2, 7, 1, 10};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文