9 | 5 | 8 | 10 | 2 | 3 |
↑low | ↑high |
可以取任意位置的值赋给val,这里取第一个位置的值9给val,val = 9;得
5 | 8 | 10 | 2 | 3 | |
↑low | ↑high |
移动high,找一个比val小的值填补low位置,high =3<val=9,high的3赋给low 得
3 | 5 | 8 | 10 | 2 | |
↑low | ↑high |
此时high不动,移动low 找一个比val大的值赋给high,向右移动,当low值为10时
3 | 5 | 8 | 10 | 2 | |
↑low | ↑high |
low=10>val=9 low的值10赋给high得
3 | 5 | 8 | 2 | 10 | |
↑low | ↑high |
此时low不动,移动high,找一个比val小的值,high向左移动
3 | 5 | 8 | 2 | 10 | |
↑low | ↑high |
high=2<val=9,high值2赋给low 得
3 | 5 | 8 | 2 | 10 | |
↑low | ↑high |
high不动了,移动low,low向右移动,此时
3 | 5 | 8 | 2 | 10 | |
↑high ↑low |
low和high在同一位置,这就是val的位置,第一次排序只能得到val的位置,
3 | 5 | 8 | 2 | 9(val) | 10 |
↑low ↑high |
重复此行为就是递归,最终就可以得到排序的结果,代码实现如下:
#include <stdio.h> void Qsort(int* a, int low, int high); int FindPos(int* a, int low, int high); int main() { int a[6] = { 9,5,8,10,2,3 }; int i; Qsort(a, 0, 5); for (i = 0; i < 6; ++i) printf("%d ", a[i]); printf("\n"); return 0; } void Qsort(int* a, int low, int high) { int pos; if (low < high) { pos = FindPos(a, low, high); Qsort(a, low, pos - 1); Qsort(a, pos + 1, high); } } int FindPos(int* a, int low, int high) { int val = a[low]; while (low < high) { while (low < high && a[high] >= val) --high; a[low] = a[high]; while (low < high && a[low] <= val) ++low; a[high] = a[low]; } a[low] = val; return low; //high == low; //return high; }