#include <stdio.h>
#include <stdlib.h>
#define SIZE 100 //元素个数
void swap(int *x,int *y) //交换两个元素
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int partition(int list[],int low,int high,int step) //进行第一次排序
{
int flag=list[low]; //将第一个元素设置为枢轴
while(high%step!=0) //从最后一个元素开始寻找与枢轴相比较的元素
{
--high;
}
while(low<high)
{
while(low<high && flag<=list[high]) //如果枢轴小于高位置的元素,则高位置减一个步长
{
high-=step;
}
if(low<high)
{
swap(&list[low],&list[high]); //枢轴小于高位置的元素则交换
swap(&list[low+1],&list[high+1]); //同时交换后面的一个元素
}
while(low<high && flag>=list[low]) //如果枢轴大于地位置的元素,则地位置加一个步长
{
low+=step;
}
if(low<high)
{
swap(&list[low],&list[high]);
swap(&list[low+1],&list[high+1]);
}
}
return low; //返回枢轴元素的位置
}
void sort(int list[],int low,int high,int step)
{
int flag;
if(low<high)
{
flag=partition(list,low,high,step); //进行一次排序后,返回一个枢轴位置
sort(list,low,flag-step,step); //将枢轴左边的元素(左边的元素都小于枢轴)递归排序
sort(list,flag+step,high,step); //将枢轴右边的元素(右边的元素都大于枢轴)递归排序
}
}
void mainSort(int list[],int low,int high,int step) //list[]数组,LOW为0,high为总的元素个数减1,step为步长为偶数
{
int index=0;
while(index<step)
{
if(index%2==0) //只排序偶数列,奇数列的元素不参加排序,只参加交换
{
sort(list+index,low,high-index,step);
}
index++;
}
}
void main(void)
{
int low=0,high,step; //step将元素分为几列,为偶数,因为是成对出现的
int i,index=0; //index排序的列数
int list[SIZE]; //SIZE元素的个数为偶数,因为交换的时候是成对交换的
for(i=0;i<SIZE;i++) //产生一个有SIZE个随机元素的数组
{
list[i]=rand()%1000;
}
high=SIZE-1;
step=6;
printf("排序前:");
for(i=low;i<=high;i++)
{
if(i%step==0)
{
printf("\n");
}
if(i%2==0)
{
printf("\t");
}
printf("%d\t",list[i]);
}
/*********************************************************************************************************/
mainSort(list,low,high,step); //排序调用此函数就可以了
//list为数组首地址,low为0,high为总的元素个数减1,step为步长为偶数
/*********************************************************************************************************/
printf("\n排序后:");
for(i=low;i<=high;i++)
{
if(i%step==0)
{
printf("\n");
}
if(i%2==0)
{
printf("\t");
}
printf("%d\t",list[i]);
}
printf("\n");
getchar();
}
多列快速排序
最新推荐文章于 2024-10-07 21:35:28 发布