Quicksort

本文详细介绍了快速排序的基本思想及其实现方式,并提供了两种不同的实现代码示例。一种是基于数组下标的实现,另一种则是使用首尾指针的方式。通过递归分割数组来实现排序,同时也提到了快速排序在极端情况下的不足。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于数组的存储中,要排序操作时,我们优先进行选择的我想就是Quicksort.

基本思想:找出分割枢轴,一趟排序将要排序的数据分割成两部分,这样一部分的所有数据都比另外一部分的所有数据都要小(大),然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列

根据数组下标

template <class Record>
void Qsort(Record* array, int low, int high) {
  //size > 2
    if(low < high) {
        int first = low;
        int last = high;
        //选取first做分割值
        int key = array[first];

        while(first < last) {
            while(first < last && array[last] >= key) {
                --last;
            }
            array[first] = array[last];

            while(first < last && array[first] <= key) {
                ++first;
            }
            array[last] = array[first];
        }

        array[first] = key;
        Qsort(array, low, first-1);
        Qsort(array, first+1, high);
    }
}
根据首尾指针
template <class Record>
void quick_sort(Record* startPointer, Record* endPointer) {
   if (startPointer < endPointer) {
       Record *bottom = startPointer, *top =  endPointer - 1;
       Record privot = *startPointer;

       while (bottom < top)  {
           while (bottom < top && *top >= privot) top--;
           if (bottom < top) {
               *bottom = *top;
               bottom++;
           }

           while (bottom < top && *bottom <= privot) bottom++;
           if (bottom < top) {
               *top = *bottom;
               top--;
           }
       }

       *bottom = privot;
       quick_sort(startPointer, bottom);
       quick_sort(bottom + 1, endPointer);
   }
}

说明:快排在最坏的情况是很糟糕的,因为我们选的都是first作为枢纽, 快排改进方法(点击)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值