快速排序和二分查找的练习

*快速排序和二分查找的练习
初始序列为:87654321
快速排序后为:12345678 (L.r[0]位置为哨兵位置,不是序列中的元素,不参与排序和输出,为快速排序特用)
二分查找(前提为有序序列)5,返回位置5*

#include <iostream.h>
typedef struct {
    int* r;
    int length;
}SqList;

#define M 8
void InitList(SqList &L,int n){
    L.r=new int[M+1]; //开辟M+1个空间,其中第0个位烧饼位
    int i;
    L.length=n;
    for(i=1;i<=n;i++){
        L.r[i]=M-i+1;//87654321
        //cout<<L.r[i]<<",";
    }
}

int find(SqList L,int key,int low,int high){
    int mid;
    while(low<=high){
        mid=(low+high)/2;
        if(L.r[mid]>key)
            high=mid-1;
        else if(L.r[mid]<key)
            low=mid+1;
        else if(L.r[mid]==key)
            return mid;
    }
    return -1;//查找失败
}
/*
int Partition ( SqList &L,int low,int  high ) 
{  
    L.r[0] = L.r[low];   
    int pivotkey = L.r[low];
    while ( low < high ) 
    { 
        while ( low < high && L.r[high] >= pivotkey )  
            --high;
         L.r[low] = L.r[high];
         while ( low < high && L.r[low] <= pivotkey )  
             ++low;
         L.r[high] = L.r[low];
     }
    L.r[low]=L.r[0]; 
    return low;
}

void QSort ( SqList &L,int low,int  high ) 
{  if  ( low < high ) 
   {
    int pivotloc = Partition(L, low, high);
    QSort(L,low,pivotloc-1);
    QSort(L,pivotloc+1,high);
   }
}

*/
int Patition(SqList &L,int low,int high){
    L.r[0]=L.r[low];
    while(low<high){
        while(low<high&&L.r[0]<=L.r[high])
            high--;
        L.r[low]=L.r[high];
        while(low<high&&L.r[0]>=L.r[low])
            low++;
        L.r[high]=L.r[low];
    }
    L.r[low]=L.r[0];
    return low;
}
void Quick(SqList &L,int low,int high){
    if(low<high){
        int pk=Patition(L,low,high);
        Quick(L,low,pk-1);
        Quick(L,pk+1,high);
    }
}
void show(SqList L){
    int i;
    for(i=1;i<=M;i++){
        cout<<L.r[i]<<",";
    }
}
void main(){
    SqList L;
    InitList(L,8);
    show(L);
    cout<<endl;
    //QSort ( L, 1, L.length ); 
    int low=1,high=M;
    Quick(L,low,high);
    show(L);
    cout<<endl;
    cout<<find(L,5,1,8)<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值