快速排序

算法思想:

  1. 从数组中抽出一个元素作为基数v(我们称之为划界元素),一般是取第一个、最后一个元素或中间的元素
  2. 将剩余的元素中小于v的移动到v的左边,将大于v元素移动到v的右边
  3. 对左右两个分区重复以上步骤直到所有元素都是有排序好。

方法一:

int Partition(int data[],int low,int high)
{
    int first=low,last=high;
    //set the first value as the pivot
    int pivot=data[first];
    while (first<last)
    {
        //check from the last back to first to find a value smaller than pivot
        while (first < last && data[last] >= pivot)
	    last--;
        //set the last value with first;
	if(first<last)
	    data[first] = data[last];
        
        //check from the first to last to find the value larger than pivot
	while (first < last && data[first]<= pivot)
	    first++;
        //set the last value to first
	if(first<last)
	    data[last]=data[first];		
    }		
    
    //put the pivot value to the first
    data[first] = pivot;
    return first;
}

void QuickSort(int data[],int low,int high)
{
    if (low>high) return;

    int first=Partition(data, low, high);
    if(first > low)
        QuickSort(data,low,first-1);
    if(first < high)
        QuickSort(data,first+1,high);
}

方法二:

void Swap(int* pLow, int* pHigh)
{
    int temp = *pHigh;
    *pHigh = *pLow;
    *pLow = temp;
}

int RandomInRange(int low, int high)
{
    int r;
    r = rand()%(high - low + 1) + low;   
    return r;
}

int Partition(int data[], int low, int high)
{
    if(data == nullptr || low < 0 || high < 0 || low < high)
        return;

    int pivot = RandomInRange(low, high);
    Swap(&data[pivot], &data[high]);

    int left = low -1;
    for(pivot = low; pivot < high; ++pivot)
    {
        if(data[pivot] < data[high])
        {    
            ++left;
            if(left != pivot)
                swap(&data[pivot], &data[left]);
        }
    }
    ++left;
    Swap(&data[left], &data[high]);
    return left;
}

void QuickSort(int data[], int low, int high)
{
    if(low == high)    
        return;

    int index = Partition(data, low, high);
    if(index > low)
        QuickSort(data, low, index -1);
    if (index < high)
        QuickSort(data, index + 1, high);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值