快速排序
- 每次选取第一个数为基准数;
- 然后使用“乾坤挪移大法”将大于和小于基准的元素分别放置于基准数两边;
- 继续分别对基准数两侧未排序的数据使用分治法进行细分处理,直至整个序列有序。
对于下面待排序的数组:
163 161 158 165 171 170 163 159 162
数 第一步:先选择第一个数 163 为基准数,以 163 为基准将小于它的数排在它前面,大于等于它
的数排在其后,结果如下:
162 161 158 159 163 170 163 171 165
此处,快速长老介绍了具体排列数据的 步骤 - 确定 163 为基准数后,先把 163 从数组中取出来
161 158 165 171 170 163 159 162 - 然后从最右端开始,查找小于基准数 163 的数,找到 162,将其移至空出来的元素中,
162 161 158 165 171 170 163 159 - 接下来,从最左边未处理的元素中从左至右扫描比基数 163 大的数,将其移动至右侧空出
来的元素中
162 161 158 171 170 163 159 165 - 接下来,继续从最右边未处理的元素中从右至左扫描比基数 163 小的数,将其移动至左侧
空出来的元素中
162 161 158 159 171 170 163 165
接下来再重复执行步骤 3,171 执行右移
162 161 158 159 170 163 171 165
重复执行步骤 4,此时右边的值已经均大于基数,左边的值均已小于基数
162 161 158 159 170 163 171 165
接下来我们将基数保存回黄色空格中
162 161 158 159 163 170 163 171 165
第二步 : 采用分治法分别对基数左边和右边的部分运用第一步中的方法进行递归操作 , 直到整个
数组变得有序,以左边的数组为例:
162 161 158 159
选择 162 为基数,运用“乾坤挪移大法”得到结果如下:
159 161 158 162
以 162 为界,把数组分成两个部分,此时,基数右侧已经没有数据,所以,接下来只要继续
对左侧的数组分治处理即可,选择 159 为基数,再次运用“乾坤挪移大法”得到结果如下:
158 159 161
代码实现
#include<stdio.h>
#include<Windows.h>
int partion(int *arr,int low,int height){
int base = arr[low];
int i = low;
int j = height;
if(low<height){
while(i<j){
while(i<j&&arr[j]>=base){
j--;
}
if(i<j){
arr[i++] = arr[j];
}
while(i<j&&arr[i]<base){
i++;
}
if(i<j){
arr[j--] = arr[i];
}
}
arr[i] = base;
}
return i;
}
void GB(int *arr,int low,int height){
if(low<height){
int index = partion(arr,low,height);
GB(arr,low,index-1);
GB(arr,index+1,height);
}
}
int main(void){
int arr[] = {163, 161, 158, 165, 171, 170, 163,159,162};
int len = sizeof(arr)/sizeof(arr[0]);
GB(arr,0,len-1);
printf("快排完毕\n");
for(int i=0;i<len;i++){
printf("%d ",arr[i]);
}
printf("\n");
system("pause");
return 0;
}