题目
解答
#include<stdio.h>
#include<math.h>
#define M 10
void BubbleSort(int s[],int n){
int i,j,tag,tmp;
for(i=n;i>=2;i--){
tag=0;
for(j=1;j<=i-1;j++){
if(s[j]>s[j+1]){
tmp=s[j];
s[j]=s[j+1];
s[j+1]=tmp;
tag=1;
}
}
if(!tag)
break;
}
}
int BinSearch(int t[],int key,int low,int high,int stack[],int *top){
int mid;
if(low>high){
stack[++(*top)]=-1;
return 0;
}
else{
mid=(low+high)/2;
stack[++(*top)]=mid;
if(key<t[mid])
return BinSearch(t,key,low,mid-1,stack,top);
else if(key>t[mid])
return BinSearch(t,key,mid+1,high,stack,top);
else
return mid;
}
}
void Output(int r[],int n){
int i;
for(i=1;i<=n;i++){
printf("%d ",r[i]);
}
printf("\n");
}
void main(){
int key=8,i,res;
int stack[M],top=-1;
int t[M+1]={0,5,6,7,8,9,10,1,2,3,4};
printf("需要排序的集合为:\n");
Output(t,M);
BubbleSort(t,M);
printf("对这10个数进行冒泡排序后(升序):\n");
Output(t,M);
res=BinSearch(t,key,1,M,stack,&top);
printf("元素%d在排序后集合中的位置为%d\n",key,res);
printf("栈中依次存储的mid值如下:\n");
for(i=0;i<=top;i++)
printf("第%d次查找的值:%d\n",i,stack[i]);
}