第3篇 快速排序
来源:互联网 发布:安卓手机数据恢复工具 编辑:程序博客网 时间:2024/06/05 18:20
The crux of the method is the partitioning process, which rearranges the array to
make the following three conditions hold:
■ The entry a[j] is in its final place in the array, for some j.
■ No entry in a[lo] through a[j-1] is greater than a[j].
■ No entry in a[j+1] through a[hi] is less than a[j].
性能:
1)将长度为N的无重复数组排序,快速排序平均需要~2NlnN次比较。
2)快速排序最多需要约N2/2次比较,但随机打乱数组能够预防这种情况。
改进:
1)对于小数组,切换到插入排序。
2)三取样切分。
#include <iostream>using namespace std;typedef void(*Fp)(int *a, int count);//快速排序统一接口void QuickSort(int *a, int count);//快速排序内部实现void quick_sort(int *a, int low, int high);//分割子程序int partition(int *a, int low, int high);//交换子程序void MySwap(int &a, int &b);const int Cnt = 10;int main(int argc, char *argv[]){ int a[Cnt] = { 23, 1, 44, 54, 76, 782, 23, 12, 43, 34 }; cout << "排序前:" << endl; for (int i = 0; i < Cnt; ++i){ cout << a[i] << " "; } cout << endl; Fp fp = QuickSort; fp(a, Cnt); cout << "排序后:" << endl; for (int i = 0; i < Cnt; ++i){ cout << a[i] << " "; } cout << endl; return 0;}void MySwap(int &a, int &b){ int tmp = a; a = b; b = tmp;}void QuickSort(int *a, int count){ //将数组a进行随机 quick_sort(a, 0, count - 1);}void quick_sort(int *a, int low, int high){ //将数组的第一项作为分割项 if (high <= low) return; int j = partition(a, low, high); //排列左边 quick_sort(a, low, j - 1); //排列右边 quick_sort(a, j + 1, high);}int partition(int *a, int low, int high){ int tmp_low = low; int tmp_high = high + 1; while (tmp_low < tmp_high){ /* *注意,左面指针遇到大于等于的元素就停下 *右面指针遇到小于等于的元素就停下 *尽管可能有一些不必要的交换 *但是能够避免算法的运行时间变为平方级的 */ while (a[++tmp_low] < a[low]); while (a[--tmp_high] > a[low]); if (tmp_high <= tmp_low) break; MySwap(a[tmp_low], a[tmp_high]); } MySwap(a[low], a[tmp_high]); return tmp_high;}//int partition(int *a, int low, int high){// int tmp = low;// while (low < high){// /*// *注意,左面指针遇到大于等于的元素就停下// *右面指针遇到小于等于的元素就停下// *尽管可能有一些不必要的交换// *但是能够避免算法的运行时间变为平方级的// */// while (a[low] <= a[tmp]) low++;// while (a[high] > a[tmp]) high--;// if (high > low) {// MySwap(a[low], a[high]);// low++;// high--;// }// }// if (high != tmp) MySwap(a[tmp], a[high]);// return high;//}
阅读全文
0 0
- 第3篇 快速排序
- 快速排序第一趟结果
- 第7章快速排序
- 第7章:快速排序
- 第 7 章 快速排序
- 3-排序-快速排序
- 算法之排序-----排序第一篇 快速排序
- 【算法导论 第7章 快速排序】
- 算法导论 第7章 快速排序
- 《算法导论》 第7章 快速排序
- 快速排序算法(第7章)
- 快速排序 and 第K大数
- 算法导论 第7章 快速排序
- 快速排序求第K小
- 算法导论-第7章 - 快速排序
- 快速排序与求第k大数
- 快速排序求第k小元素
- 第16周 项目1-快速排序
- 【翻译】ASP.NET Core 文档目录
- 网易2018年编程题
- hadoop集群搭建
- 为什么匿名内部类和局部内部类只能访问final变量
- 传纸条
- 第3篇 快速排序
- 基于scp协议向linux发送文件
- Codeforces Round #374 (Div. 2) D. Maxim and Array 贪心
- 670. Maximum Swap
- 最小二乘法及其拟合
- Spring学习之——控制反转(IoC)与依赖注入(DI)
- git如何删除已经 add 的文件 (如何撤销已放入缓存区文件的修改)
- 【Android】【TP】TP开发常见问题&分析
- JavaScript中七种函数调用方式及对应 this 的含义