递归版本
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quickSortRecursive(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSortRecursive(arr, low, pi - 1);
quickSortRecursive(arr, pi + 1, high);
}
}
迭代版本 (使用 std::stack)
#include
#include
int partition(int arr[], int low, int high);
void quickSortIterative(int arr[], int low, int high) {
std::stackint, int>> st;
st.push({low, high});
while (!st.empty()) {
low = st.top().first;
high = st.top().second;
st.pop();
int pi = partition(arr, low, high);
if (pi - 1 > low) {
st.push({low, pi - 1});
}
if (pi + 1 < high) {
st.push({pi + 1, high});
}
}
}