代码改变世界

快速排序算法

2017-05-18 17:27  sinohenu  阅读(162)  评论(0)    收藏  举报

根据百度百科介绍:

快速排序(Quicksort)是对冒泡排序的一种改进。
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列
算法的难点就是递归思想的应用,另外一个就是定位基准元素的位置。
举例如下:
[4,3,9,8,5,1]
第一步:
  将4作为基准,与其余元素比较,小于4的元素在左边,大于4的元素在右边;遍历后的结果为:3,1,4,9,8,5; 基准4已经在正确的排序位置上。
第二步:
  再递归对[3,1]排序,将3作为基准,小于3的元素在左边,大于3的元素在右边;遍历后的结果为:1,3;排序完毕,返回排序结果[1,3];同理,子序列[9,8,5]排序的结果也为[5,8,9]
第三步:
  递归层层返回,排序后的结果为[1,3,4,5,8,9].
算法时间复杂度为O(NlogN).

代码如下:

#include <iostream>
using namespace std;

void swap(int& a, int& b)
{
	a += b;
	b = a - b;
	a = a - b;
}

void Dump(int a[], int size)
{
	for(int i = 0; i < size; ++i)
		cout << a[i] << " ";
	cout << endl;
}
void QuickSort(int array[], int low, int high)
{
	if(low >= high)
		return;
	int pivot = array[low];
	int storedIndex = low ;
	for(int j = low + 1; j <= high; ++j)
	{
		if(array[j] <= pivot)
		{
			++storedIndex;
			if(storedIndex != j)
			{
				swap(array[storedIndex], array[j]);
			}
		}
	}
	if(storedIndex != low )
		swap(array[storedIndex],array[low]);
	QuickSort(array, low,storedIndex-1);
	QuickSort(array, storedIndex+1,high);
}

int main()
{
	int a[] = {27,11,8,49,14,27,19,5,18,35,50,32,32,18,38,18,23,32,37};
#define ARRAY_SIZE (sizeof(a)/sizeof(int))
	QuickSort(a, 0, ARRAY_SIZE -1);
	Dump(a,ARRAY_SIZE);
#ifdef WIN32
	getchar();
#endif
#undef ARRAY_SIZE
	return 0;
}