[原]C语言实现的快速排序,采用分治策略,递归实现

#include<stdio.h>
#define LEN 8
int a[LEN] = { 5, 2, 4, 7, 1, 3, 2, 6 };

int Partition(int a[],int p,int r);
void Swap(int *a,int *b);

void QuickSort(int a[],int p,int r)
{
	if(p<r)
	{
		int q=Partition(a,p,r);//q是当前划分点
		printf("当前Q的值是:%d\n",a[q]);
		for(int i=0;i<LEN;i++)
		{
			printf("%d,",a[i]);
		}
		printf("\n");
		QuickSort(a,p,q-1);
		QuickSort(a,q+1,r);
	}
}
int Partition(int a[],int p,int r)
{
	printf("当前P的值是:%d\n",a[p]);
	int i=p,j=r+1;//i指向了数组的第一个数,j指向了数组的最后一个数
	int x=a[p];//x现在的值是数组a的第一个值,x是基准元素

	while(1)
	{
		while(a[++i]<x&&i<r);//一直往下找,找到比x小的数,继续程序,要注意i不能越界
		while(a[--j]>x);//继续往前找,找到比x大的数,继续程序
		if(i>=j)break;//
		Swap(&a[i],&a[j]);//
	}
	a[p]=a[j];
	a[j]=x;
	return j;
}
void Swap(int *a,int *b)
{
	int temp;
	temp=*a;
	*a=*b;
	*b=temp;
}
int main()
{
	printf("待排数组为:\n");
		for(int i=0;i<LEN;i++)
		{
			printf("%d,",a[i]);
		}
		printf("\n");
	QuickSort(a,0,LEN-1);
}

作者:gcy77 发表于2014-3-17 9:27:59 原文链接
阅读:136 评论:0 查看评论
posted @ 2014-03-17 09:28  Murderer  阅读(285)  评论(0编辑  收藏  举报