多列快速排序

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值