算法原理
簡單說來,就是分而治之,現在隨意取一個值作爲基準對照值,
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);
}
}
}
}
推薦課程
尹成老師帶你學算法
數據結構核心原理與算法應用