第3篇 快速排序

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值