1 利用快速排序实现从小到大排序
定义一个数组Arr 如下:
9 0 8 10 -5 2 13 7
^——————— ^
Low__________High
1、定义一个变量 val 存储 Arr[Low]的值
2、先移动High
High移动规则:
如果Arr[High]>=val,则将High位置前移,即:
--High;
9 0 8 10 -5 2 13 7
^____________ ^
Low__________High
如果Arr[High]<val,则将Arr[High]的值赋值给Arr[Low],即 Arr[Low]=Arr[High];
7 0 8 10 -5 2 13 7
^__________ ___ ^
Low___________High
3、再移动Low
Low移动规则:
如果Arr[Low]>=val,则将位置后移,即:
++Low;
7 0 8 10 -5 2 13 7
+++++^_______ ^
+++++Low_____High
如果Arr[Low]>val,则将Arr[Low]的值赋值给Arr[High],即 Arr[High]=Arr[Low];
7 0 8 10 -5 2 13 10
+++++^_______ ^
+++++Low_____High
4、继续移动High 与 Low
5、只到Low =High时,停止本次排序,并将Arr[Low]或者Arr[High]的值赋值为Val
7 0 8 10 -5 2 13 10
++++++++ ^ ^
++++++++ L H
都指向2
此时将Arr[L]=val 或者Arr[High]=val
7 0 8 10 -5 9 13 10
++++++++ ^ ^
++++++++ L H
此时,就是将9的位置找到
6、一次结束只能将val的正确位置找到
程序代码如下
#include <stdio.h>
int FindPos(int *a, int low, int high);
void QuickSort(int * a, int low, int high);
int main() {
int a[]={1,12,5,98,14,25,36,27,10};
for (int i = 0; i < sizeof(a)/sizeof(a[0]); ++i) {
printf("a[%d]=%d\n",i,a[i]);
}
QuickSort(a,0,sizeof(a)/sizeof (a[0]));
printf("排序后=======");
for (int i = 0; i < sizeof(a)/sizeof(a[0]); ++i) {
printf("a[%d]=%d\n",i,a[i]);
}
}
void QuickSort(int * a, int low, int high)
{
int pos;
if (low<high)
{
pos =FindPos(a,low,high);
QuickSort(a,low,pos-1);
QuickSort(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;
}