您的位置:首页 > 其它

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

2010-09-11 16:38 585 查看
/*
2010-9-11
快速排序和二分查找的练习
初始序列为: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: