【搬运】浙大 数据结构 快速排序

#include <iostream>

using namespace std;

int Cutoff = 50;<span style="white-space:pre">	</span>//阈值(可自己调整),低于该阈值使用插入排序更加快捷

void swap(int *a, int *b){
    int temp = *b;
    *b = *a;
    *a = temp;
}

void InsertionSort(int A[],int left,int right)
{
    for (int i=left-1; i<=right; i++)
    {
        int inserter = A[i];
        int index = i;
        
        for ( ;index > 0 && A[index-1] > inserter;index--)
            A[index] = A[index-1];
        A[index] = inserter;
    }
}

int Median(int A[], int left, int right){<span style="white-space:pre">	</span>//选主元,取头、中、尾的中位数作为主元
    int Center = ( left + right ) / 2 ;
    if ( A[left] > A[Center] )
        swap( &A[left] , &A[Center] );
    if ( A[left] > A[right] )
        swap( &A[left] , &A[right] );
    if ( A[Center] > A[right] )
        swap( &A[Center] , &A[right] );
    swap( &A[Center] , &A[right - 1] ); <span style="white-space:pre">	</span>//将主元藏在倒数第二位,便于中间的数排序
    
    return A[right - 1];
}

void Quicksort(int A[], int left, int right){ <span style="white-space:pre">	</span>//快速排序的递归实现
    if ( (right - left) > Cutoff){
        if ( left < right ){
            int Pivot = Median(A, left, right);
            int i = left;
            int j = right - 1;
            
            for ( ; ; ){
                while ( A[++i] < A[Pivot] ){}
                while ( A[--j] > A[Pivot] ){}
                if ( i < j )
                    swap( &A[i] , &A[j] );
                else break;
            }
            
            swap( &A[i] , &A[right - 1] );
            
            Quicksort(A,left,i-1);
            Quicksort(A,i+1,right);
        }
    }
    
    else
        InsertionSort(A,left,right);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值