快速排序(C语言)

快速排序

快速排序的基本思想是:

1.先从数列中取出一个数作为基准数。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。
优化前的代码:

//简单选择排序
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 10

typedef struct
{
	int r[MAXSIZE];
	int length;
}SqList;

void swap(SqList * L,int i, int j)
{
	int temp = L->r[i];
	L->r[i] = L->r[j];
	L->r[j] = temp;
}


int  KeyPoint(SqList * L, int low, int high)
{
	int KeyPoint;

	int m = low + (high - low)/2;

	KeyPoint = L->r[low];

	while(low<high)
	{
		while(low<high && L->r[high]>=KeyPoint)
		{
			high--;
		}
		
		swap(L,low,high);

		while(low<high && L->r[low]<=KeyPoint)
		{
			low++;
		}
		L->r[high] = L->r[low];
		swap(L,low,high);
	}
	L->r[low] = L->r[0];

	return low;
}



void Qsort( SqList * L, int low, int high )
{
	int point;

	if( low<high )
	{
		point = KeyPoint(L, low, high);
		
		Qsort( L, low, point-1 );
		Qsort( L, point+1, high );
	}
}

void QuickSort(SqList * L)
{
	Qsort( L, 1, L->length );
}

//测试
int main(void)
{
	int i;
	SqList * L = (SqList *)malloc(sizeof(SqList));
	L->length = 8;

	L->r[0] = 0;
	L->r[1] = 5;
	L->r[2] = 7;
	L->r[3] = 8;
	L->r[4] = 3;
	L->r[5] = 4;
	L->r[6] = 6;
	L->r[7] = 1;
	L->r[8] = 2;

	QuickSort(L);

	for( i = 1; i<=L->length; i++)
	{
		printf("%d\n",L->r[i]);
	}

	return 0;
}

因为每一次swap操作的效率还是比较低的,所以找一个“哨兵”用来做赋值操作。另外如果数组中的数字本来就是有序的,那快速排序的优势就没有了。
优化后的代码:

//简单选择排序
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 10

typedef struct
{
	int r[MAXSIZE];
	int length;
}SqList;

int  KeyPoint(SqList * L, int low, int high)
{
	int KeyPoint;

	int m = low + (high - low)/2;

	if(L->r[low]>L->r[high])
		swap(L,low,high);
	if(L->r[m]>L->r[high])
		swap(L,high,m);
	if(L->r[m]>L->r[low])
		swap(L,m,low);


	KeyPoint = L->r[low];

	L->r[0] = KeyPoint; 

	while(low<high)
	{
		while(low<high && L->r[high]>=KeyPoint)
		{
			high--;
		}
		L->r[low] = L->r[high];
		//swap(L,low,high);

		while(low<high && L->r[low]<=KeyPoint)
		{
			low++;
		}
		L->r[high] = L->r[low];
		//swap(L,low,high);
	}
	L->r[low] = L->r[0];

	return low;
}



void Qsort( SqList * L, int low, int high )
{
	int point;

	if( low<high )
	{
		point = KeyPoint(L, low, high);
		
		Qsort( L, low, point-1 );
		Qsort( L, point+1, high );

	}
}


void QuickSort(SqList * L)
{
	Qsort( L, 1, L->length );
}


int main(void)
{
	int i;
	SqList * L = (SqList *)malloc(sizeof(SqList));
	L->length = 8;

	L->r[0] = 0;
	L->r[1] = 5;
	L->r[2] = 7;
	L->r[3] = 8;
	L->r[4] = 3;
	L->r[5] = 4;
	L->r[6] = 6;
	L->r[7] = 1;
	L->r[8] = 2;

	QuickSort(L);

	for( i = 1; i<=L->length; i++)
	{
		printf("%d\n",L->r[i]);
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值