第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;//}
原创粉丝点击