快排算法

《剑指offer》解法

void Quicksort(int data[],int start,int end)  
{  
    if(start==end)  
    {  
        return ;  
    }  
    int index=Partition(data,start,end);  
    if(index>start)  
        Quicksort(data,start,index-1);  
    if(index<end)  
        Quicksort(data,index+1,end);  
} 

int Partition(int data[],int start,int end)  
{  
    if(data==NULL ||start<0 || end>=length)    
        exit(0);

    int index=RandomInRange(start,end);  

    swap(&data[index],&data[end]);  
    int small=start-1;  
    for(index=start;index<end;index++)  
    {  
       if(data[index]<data[end])  
        {  
            ++small;  
            if(small != index)  
            {  
                swap(&data[index],&data[small]);  
            }  
        }  
    }  
    ++small;  
    swap(&data[small],&data[end]);  
    return small;  
}  


《大话数据结构》解法

/* 对顺序表L作快速排序 */
void QuickSort(SqList *L)
{ 
    QSort(L,1,L->length);
}

/* 对顺序表L中的子序列L->r[low..high]作快速排序 */
void QSort(SqList *L,int low,int high)
{ 
    int pivot;
    if(low<high)
{
    pivot=Partition(L,low,high);  /* 将L->r[low..high]一分为二,算出枢轴值pivot */
    QSort(L,low,pivot-1);   /*  对低子表递归排序 */
    QSort(L,pivot+1,high);   /*  对高子表递归排序 */
 }
}

/* 交换顺序表L中子表的记录,使枢轴记录到位,并返回其所在位置 */

/* 此时在它之前(后)的记录均不大(小)于它。 */
int Partition(SqList *L,int low,int high)
{ 
    int pivotkey;
    pivotkey=L->r[low];  /* 用子表的第一个记录作枢轴记录 */
    while(low<high)      /* 从表的两端交替地向中间扫描 */
    { 
       while(low<high&&L->r[high]>=pivotkey)
           high--;
       swap(L,low,high); /* 将比枢轴记录小的记录交换到低端 */
       while(low<high&&L->r[low]<=pivotkey)
           low++;
       swap(L,low,high); /* 将比枢轴记录大的记录交换到高端 */
    }
     return low;     /* 返回枢轴所在位置 */
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值