`
v5qqbrowser
  • 浏览: 358056 次
文章分类
社区版块
存档分类
最新评论

C语言 ---- 快速排序算法

 
阅读更多
#include <stdio.h>

/*
	关键在于:确定第一个元素的位置,左边都是比这个元素小的,右边是大的,然后
	递归进行左右边 分别 确定各自第一个元素的位置
  */
void QuickSort(int *a, int low, int high);
int FindPos(int *a, int low, int high);
int main(void)
{
	int a[6] = {2,-21,0,-5,34,3};

	int i;

	QuickSort(a,0,5);
	
	for(i=0; i<6; i++)
	{
		printf("%d ", a[i]);

	}

	printf("\n");
	return 0;
}

void QuickSort(int *a, int low, int high)
{
	int pos;

	if(low<high)
	{
		pos = FindPos(a, low, high);
		QuickSort(a, low, pos-1);
		QuickSort(a, pos+1, high);
	}
}

int FindPos(int *a, int low, int high)
{
	int val = a[low];

	while(low < high)
	{
		//右边指针开始时指向最后一个元素,如果比第一个元素大,就往左移动
		//遇到小的,则停住,和左边指针交换值,左边指针开始移动
		while(low<high && a[high]>=val)
		{
			--high;
		}
		a[low] = a[high];

		//和上边逻辑一样,遇到比第一个元素小的就移动,大的停止,然后交换
		while(low<high && a[low]<=val)
		{
			++low;
		}
		a[high] = a[low];
	}

	a[low] = val;//或者a[high] = val;low==high

	return high; //low也可以,low==high
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics