算法原理
简单说来,就是分而治之,现在随意取一个值作为基准对照值,
1 从右往左,直到遇到第一个大于对照值的,与对照值交换位置
2 从左往右,直到遇到第一个小于对照值的,与对照值交换位置
3 重复 1/2 步骤,直到左右指针相遇,退出
4 从相遇位置为分割线,将两个数组重复进行 1/2/3 步骤,直到全部都结束
递归方式排序
eg
数组: 6 8 2 9 33 2 3
第一次:
取左侧第一个值为对照值 (tmp = array[p_tmp])tmp = 6 p_tmp = 0 (tmp 所在位置指针)
右边开始 rp >= p_tmp 3 < 6 Yes 交换 3 8 2 9 33 2 6 // tmp = 6, p_tmp = 6 rp = 6
左边开始 lp <= p_tmp 3 > 6 NO; 8 > 6 Yes 交换 3 6 2 9 33 2 8 // tmp = 6, p_tmp = 1 lp = 1
rp >= lp Yes 继续
右边开始 rp >= p_tmp 2 < 6 Yes 交换 3 2 2 9 33 6 8 // p_tmp = 5, rp = 5
左边开始 lp <= p_tmp 2 > 6 No; 2 > 6 NO; 9 > 6 Yes 交换 3 2 2 6 33 9 8 // p_tmp = 3, lp = 3
rp >= lp Yes 继续
右边开始 rp >= p_tmp 9 < 6 No; 33 < 6 No; 6 < 6 NO; rp < p_tmp 结束
左边开始 lp <= p_tmp 6 > 6 NO; lp > p_tmp 结束
rp >= lp 结束
array[p_tmp]= tmp;
p_tmp - left > 1
递归左侧 array, left, p_tmp-1
right - p_tmp > 1
递归右侧 array, p_tmp+1, right
直到结束,以上规定方式
递归方式源码
void sort_quick_r(int array[], int left, int right)
{
int tmp = array[left];
int p = left;
int i = left, j = right;
while (i <= j) {
while (array[j] <= tmp && j > p) // <= 降序 >= 升序 array[i] >= tmp
j--;
if (j >= p) {
array[p] = array[j];
p = j;
}
while (array[i] >= tmp && i < p) // >= 降序 <= 升序 array[i] >= tmp
i++;
if (i <= p) {
array[p] = array[i];
p = i;
}
}
array[p] = tmp;
if (p - left > 1)
sort_quick_r(array, left, p-1);
if (right - p > 1)
sort_quick_r(array, p+1, right);
}
非递归方式源码
#include <stack>
using namespace std;
int sort_quick_normal(int array[], int left, int right)
{
int p = array[right];
while (left < right) {
//升序
while (array[left] < p && left < right) { //array[left] > p 降序
left++;
}
if (left < right)
array[right--] = array[left];
while (array[right] > p && left < right) {//array[left] < p 降序
right--;
}
if (left < right)
array[left++] = array[right];
}
array[left] = p;
return left;
}
void sort_quick(int array[], int left, int right)
{
std::stack <int> s;
if (left < right) {
int boundary = sort_quick_normal(array, left, right);
if (boundary - 1 > left) {
s.push(left);
s.push(boundary - 1);
}
if (boundary + 1 < right) {
s.push(boundary + 1);
s.push(right);
}
while (!s.empty()) {
int r = s.top();
s.pop();
int l = s.top();
s.pop();
boundary = sort_quick_normal(array, l, r);
if (boundary-1>l) {
s.push(l);
s.push(boundary-1);
}
if (boundary + 1 < r) {
s.push(boundary + 1);
s.push(r);
}
}
}
}
推荐课程
尹成老师带你学算法
数据结构核心原理与算法应用