【算法图解】:数据结构教程李春葆版P378
1. 递归代码:
#include<iostream>
#include<vector>
using namespace std;void quicksort(vector<int> &v, int left, int right)
{if (left < right){int key = v[left];int low = left;int high = right;while (low < high){while(low < high && v[high] >= key)high--;v[low] = v[high];while (low < high && v[low] < key)low++;v[high] = v[low];}v[low] = key;quicksort(v, left, low - 1);quicksort(v, low + 1, right);}
}int main()
{vector<int> num = { 6, 8, 7, 9, 0, 1, 3, 2, 4, 5 };quicksort(num, 0, num.size() - 1);for (auto c : num)cout << c << " ";cout << endl;return 0;
}
2. 非递归版本:
#include<iostream>
#include<vector>
#include<stack>
using namespace std;void quicksort(vector<int> & arr, int length)
{stack<int> lowHigh;//先存大再存小,取得时候就可以先取小再取大,此处的大小指的是数组索引lowHigh.push(length - 1);lowHigh.push(0);int low, high;while (!lowHigh.empty()){low = lowHigh.top(); lowHigh.pop();high = lowHigh.top(); lowHigh.pop();if (low >= high)continue;int i = low; int j = high;int value = arr[low];while (i < j)//i==j循环结束{while (arr[j] > value)j--;//右边的都大于valuestd::swap(arr[j], arr[i]);while (arr[i] < value)i++;//左边的都小于valuestd::swap(arr[i], arr[j]);}//开始存储左右两侧待处理的数据,为了先处理左侧先保存右侧数据lowHigh.push(high);lowHigh.push(i + 1);//左侧lowHigh.push(i - 1);lowHigh.push(low);}
}int main()
{vector<int> data = { 6, 8, 7, 9, 0, 1, 3, 2, 4, 5 };quicksort(data, data.size());for (int i = 0; i < 10; ++i)printf("%d ", data[i]);return 0;
}