C语言快速排序(郝斌老师笔记)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值