您的位置:首页 > 产品设计 > UI/UE

快速排序算法QuickSort

2011-09-21 16:15 281 查看
// QuickSort.cpp : 定义控制台应用程序的入口点。
//快速排序算法实现
/*设要排序的数组是A[0]……A[N-1],首先任意选取一个数据(通常选用第一个数据)作为关键数据,
然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序。
然后,对前面部分比它小的数继续进行快速排序;也对后面部分比它大的数继续进行快速排序。
值得注意的是,快速排序不是一种稳定的排序算法,也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。
*/
#include "stdafx.h"
#include <iostream>
using namespace std;

void quickSort(int *a,int low,int high)
{
//int a[25] ={1455,23,433,335,6,4567,7,8,9423,5565,773,234,1315,7,88,5345,2526,67574,12315,6786,123123,2131,34355,6784,3456};
int key = a[low];//以a[low]为枢纽值、关键数据
int l=low;
int h =high;
if(low>=high)
return;
while(l < h)
{
//一趟快速排序
//这两个循环的次序不能颠倒
while(l < h && a[h]>= key )
{
h--;
}
a[l] = a[h];

while(l < h && a[l]<= key )
{
l++;
}
a[h] = a[l];
}
a[l]=key;//放置枢纽值

//分别对左边、右边排序
quickSort(a,low,l-1);
quickSort(a,l+1,high);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[25] ={1455,23,433,335,6,4567,7,8,9423,5565,773,234,1315,7,88,5345,2526,67574,12315,6786,123123,2131,34355,6784,3456};

////把比关键数据小的放在前面,比关键数据大的放在后面
//int key = a[0];
//int l = 0,h = 24;
//while(l < h)
//{
//	while(a[h] >= key)
//		h--;
//	a[l] = a[h];

//	while(a[l] <= key)
//		l++;
//	a[h] = a[l];
//}
//a[l] = key;

quickSort(a,0,24);
for (int i = 0; i<25;i++)
{

cout <<"a["<<i <<"]:"<<a[i] <<endl;

}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: