快速排序 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是就地排序的,所以不需要合并操作
Quick-Sort的C++实现如下:
算法描述:
分解(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++实现如下:
相关文章推荐
- 快速排序:Quicksort(2)
- 快速排序——QuickSort——Python
- 第七章快速排序之“快速排序的随机化版本RANDOM-QUICKSORT”
- 快速排序(QuickSort)
- 快速排序QuickSort
- 【数据结构】快速(QuickSort)排序之——前后指针法
- 快速排序(QuickSort)
- QuickSort 快速排序
- QuickSort 快速排序
- 快速排序在Top k问题中的运用(quickSort and quickSelect in Top k)
- QuickSort快速排序
- Python--递归和快速排序 -- quickSort
- 算法导论 - QuickSort 快速排序 C++实现
- DualPivotQuickSort 双轴快速排序 源码
- 快速排序(Quicksort)的Javascript实现
- 快速排序-Quicksort
- quickSort - 快速排序
- 算法导论学习--快速排序--Quicksort
- 快速排序_QUICKSORT
- 快速排序Quicksort Array in Java