快排算法

《剑指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(indexindex+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;indexindex++)  
    {  
       if(data[index]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/* 将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/* 从表的两端交替地向中间扫描 */
    { 
       while(lowr[high]>=pivotkey)
           high--;
       swap(L,low,high); /* 将比枢轴记录小的记录交换到低端 */
       while(lowr[low]<=pivotkey)
           low++;
       swap(L,low,high); /* 将比枢轴记录大的记录交换到高端 */
    }
     return low;     /* 返回枢轴所在位置 */
}

你可能感兴趣的:(算法)