Re:从零开始的算法学习【4】快速排序

快速排序:对冒泡排序的一种改进。通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,过程可以递归进行。
#include<iostream>
using namespace std;


void qsort(int *a,int start,int end)
{
	 if(start >= end) return;	//停止递归
	int i = start;
	int j = end;
	int key = a[i];		//基准位
	
	while(i<j)
	{
		while(i<j&&a[j]>=key)
		{
			j--;
		}
		a[i] = a[j];
		
		while(i<j&&a[i]<=key)
		{
			i++;
		}
		a[j] = a[i];
	}
	a[i] = key; //»òÕßa[j] = key;
	qsort(a,start,i-1);	//对左右两边分别进行快排 
	qsort(a,i+1,end); 
}

void display(int *a,int n)
{
	for(int i =0;i<n;i++)
	{
		cout << a[i] << ",";
	}
	cout << endl;
}

int main()
{
	const int N = 10;
	int a[N] = {1,4,3,2,6,5,9,7,8,10};
	qsort(a,0,N-1);
	display(a,N);
	return 0 ;
 } 

猜你喜欢

转载自blog.csdn.net/vincemar/article/details/80239789