快速排序法
简述
快速排序法在程序运行时具有平均运行时间短的优势,并且在内存使用 、程序实现复杂性上表现优秀,使得快速排序法在一般情况下成为最实用的排序方法之一。
原理
注:以从左到右从小到大排列为例。
设置一个基准,将比基准大的数据放在基准的右边,比基准小的数据放在基准的左边,并进行递归操作反复选取基准并反复移动数据,达到排序的目的。
代码示例(C语言)
int QuickSort(int *arr,int left,int right)//快速排序法 (指定数组,数组左端,数组右端)
{
int f,t;//设置基准和中间量(交换数据时使用)
int rtemp,ltemp;//设右当前指向数组的位置(以下称右当前)和左当前指向数组的位置(以下称左当前)
ltemp=left;//初始令左当前为数组最左端
rtemp=right;//初始令右当前为数组最右端
f=arr[(left+right)/2];//不妨设基准为数组中间位置的数据(偶数个数据的数组为中间靠左的位置)
while(ltemp<rtemp)//当左当前在右当前左端时,进行循环
{
while(arr[ltemp]<f)//当左当前位置对应数据小于基准时,进行循环
{
++ltemp;//使左当前向右移一位
}//直到左当前位置对应数据大于基准时跳出循环,此时应该将此数据交换到基准右边
while(arr[rtemp]>f)//当右当前位置对应数据大于基准时,进行循环
{
--rtemp;//使右当前向左移一位
}//直到右当前位置对应数据小于基准时跳出循环,此时应该将此数据交换到基准左边
if(ltemp<=rtemp)//此时应进行数据交换,判断左当前是否还在右当前左边,若是则进行以下步骤
{
t=arr[ltemp];
arr[ltemp]=arr[rtemp];
arr[rtemp]=t;//以上三行为交换左当前和右当前分别对应的数据
--rtemp;//右当前左移一位
++ltemp;//左当前右移一位
}//若此判断条件不成立,则可直接进行以下步骤
}
if(ltemp==rtemp)//排除左当前和右当前指向同一位置的干扰
ltemp++;
if(left<rtemp)//若右当前仍未移到数组最左端
QuickSort(arr,left,ltemp-1);//运用递归的方式将数组左端和左当前-1之间的数据重新排序
if(ltemp<right)//若左当前仍未移到数组最右端
QuickSort(arr,rtemp+1,right);//运用递归的方式将数组右当前+1和右端之间的数据重新排序
//重复使用递归后排序结束
return 0;
}
应用实例——花式排序(整数)
问题描述
从键盘输入10个整数,按如下要求实现对整型数组中的元素进行排序:将下标为奇数的数据按降序(从大到小)排序,将下标为偶数的数据按升序排列。将排序后的结果输出,每个整数之间使用空格进行分隔。
例如输入:
0 1 2 3 4 5 6 7 8 9
输出:
0 9 2 7 4 5 6 3 8 1
解题代码
#include<stdio.h>
int QuickSort(int *arr,int left,int right);
int main()
{
int a[10];
int b[5];
int c[5];
int i,j,k,l;
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
j=0;
l=0;
for(k=0;k<10;k++)
{
if(k%2!=0)
{
b[j]=a[k];
j=j+1;
}
if(k%2==0)
{
c[l]=a[k];
l=l+1;
}
}
QuickSort(b,0,4);
QuickSort(c,0,4);
for(j=4,l=0;j>0,l<5;j--,l++)
{
printf("%d %d ",c[l],b[j]);
}
return 0;
}
int QuickSort(int *arr,int left,int right)
{
int f,t;
int rtemp,ltemp;
ltemp=left;
rtemp=right;
f=arr[(left+right)/2];
while(ltemp<rtemp)
{
while(arr[ltemp]<f)
{
++ltemp;
}
while(arr[rtemp]>f)
{
--rtemp;
}
if(ltemp<=rtemp)
{
t=arr[ltemp];
arr[ltemp]=arr[rtemp];
arr[rtemp]=t;
--rtemp;
++ltemp;
}
}
if(ltemp==rtemp)
ltemp++;
if(left<rtemp)
QuickSort(arr,left,ltemp-1);
if(ltemp<right)
QuickSort(arr,rtemp+1,right);
return 0;
}