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

快速排序 QuickSort

2010-05-04 16:01 387 查看
快速排序通常用于排序的最佳的使用选择,其期望运行时间为:O(nlgn)能够进行就地排序。最坏运行时间为:O(n^2)
算法描述:
分解(divide:数组A[beg…end]被划分为两个子数组A[beg…mid - 1]和A[mid + 1…end],使得A[beg…mid - 1]中的数据都小于A[mid],A[mid + 1…end]中的数据都大于A[mid]
解决(conquer:递归地调用QuickSort
合并(combine:因为QuickSort是就地排序的,所以不需要合并操作
#include <iostream>

void QuickSort(int a[], const int &begin, const int &end);
int Partition(int a[], const int &beg, const int &end);
int main()
{
int size;		//	the size of array

std::cout << "Input the size of array:" << std::endl;
std::cin >> size;

int *a = new int[size]();		//new an array of the size

for (int i = 0; i < size; i++)
{
std::cin >> a[i];
}

QuickSort(a, 0, size - 1);

std::cout << std::endl << "Output the result of heap:" << std::endl;
for (int i = 0; i < size; i++)
{
std::cout << a[i] << " ";
}
delete []a;
return 0;
}

/*************************************************
Function: QuickSort
Description:对指定数组中的元素进行从小到大的排序,其中调用了Partition函数来对数组进行划分
Input:	a[] 指定数组
const begin 数组元素的开始序号
const end 数组元素的结束序号
*************************************************/
void QuickSort(int a[], const int &begin, const int &end)
{
if (begin >= end)
{
return;
}

else if ((begin + 1) == end)
{
if (a[begin] > a[end])
{
int temp = a[begin];
a[begin] = a[end];
a[end] = temp;
}
return;
}
else
{
int mid = Partition(a, begin, end);
Partition(a, begin, mid - 1);
Partition(a, mid + 1, end);
}
}

/*************************************************
Function: Partition
Description:对数组元素按指定的数划分成两个不同集合
Calls: 无
Input:	a[] 指定数组
const beg 数组元素的开始序号
const end 数组元素的结束序号
Return:指定元素划分后的序号
Others:end >= beg + 2
*************************************************/
int Partition(int a[], const int &beg, const int &end)
{
//int key = a[end];
int part = beg - 1;
for (int i = beg; i < end - 1; i++)
{
if (a [beg] < a[end])
{
part++;
if (part != i)
{
int temp = a[i];
a[i] = a[part];
a[part] = temp;
}
}
}

part++;
int temp = a[end -1];
a[end - 1] = a[part];
a[part] = temp;

return part;
}

Quick-Sort的C++实现如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: