您的位置:首页 > 编程语言 > C语言/C++

c语言快速排序与二分查找算法

2014-06-19 21:01 204 查看
#include<stdio.h>
int r[20];
int Quick_Partition(int r[],int a,int b);
int Binary_serch(int r[],int key,int n);
void Quick_Sort(int r[],int s,int t);

int main(void){

int i=0,j=0,bi,ans;
printf("请输入待排序数据:(0结束)");
do{
scanf("%d",&r[j]);
j++;
}while(r[j-1]!=0);
j=j-2;
Quick_Sort(r,i,j);
while(i<=j){
printf("%d ",r[i]);
i++;
}
for(;;){
printf("请输入您要查找的数据:(0表示结束)");
scanf("%d",&bi);
if(bi==0){
printf("查找结束\n");
return 0;
}
else{
ans=Binary_serch(r,bi,j);
if(ans==-1){
printf("在数组中没有找到%d\n",bi);
}
else{
ans=ans+1;
printf("查找成功\n");
printf("在数组中第%d个位置找到%d\n",ans,bi);
}
}

}
return 0;
}

int Quick_Partition(int r[],int a,int b){
int temp;
temp=r[a];
while(a<b){
while(a<b&&r[b]>=temp)b--;
if(a<b)
{
r[a]=r[b];
a++;
}
while(a<b&&r[a]<=temp)a++;
if(a<b)
{
r[b]=r[a];
b--;
}
}
r[a]=temp;
return a;
}

void Quick_Sort(int r[],int s,int t){
int i;
while(s<t){
i=Quick_Partition(r,s,t);
Quick_Sort(r,s,i-1);
Quick_Sort(r,i+1,t);
s++;
}

}

int Binary_serch(int r[],int key,int n){
int low=0;
int high=n;
int mid;
while(low<=high){
mid=(low+high)/2;
if(key==r[mid]){
return mid;
}
else if(key>r[mid]){
low=mid+1;
}
else{
high=mid-1;
}

}
return -1;
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: