代码
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int SqSearch(int r[],int n, int key){
int i;
for(i=0;i<n;i++){
if(r[i] == key){
return i+1;
}
}
return 0;
}
void swap(int r[],int i,int j){
int tmp = r[i];
r[i] = r[j];
r[j] = tmp;
}
int partition(int r[],int low, int high){
int privotKey = r[low];
while(low<high){
while(low<high && r[high]>=privotKey)high--;
swap(r,low,high);
while(low<high && r[low]<=privotKey)low++;
swap(r,low,high);
}
return low;
}
void quickSort(int r[],int low,int high){
if(low<high){
int privotLoc = partition(r,low,high);
quickSort(r,low,privotLoc-1);
quickSort(r,privotLoc+1,high);
}
}
void print(int r[], int n){
int i;
for(i=0;i<n;i++){
printf("%5d",r[i]);
if((i+1)%10==0)printf("\n");
}
printf("\n");
}
int binarySearch(int r[],int n, int key){
int low,high,mid;
low = 0;
high = n;
while(low<=high){
mid = (low+high)/2;
if(key == r[mid]){
return mid+1;
}else if(key<r[mid]){
high = mid-1;
}else{
low = mid+1;
}
}
return (-1);
}
int main(){
int i;
int r[100],key;
key = 63;
printf("需要查找的数据:\n");
for(i=0;i<100;i++){
r[i] = rand()%100+1;
printf("%5d",r[i]);
if((i+1)%10 == 0){
printf("\n");
}
}
printf("顺序表查找:");
printf("%d的位置在:%3d\n\n",key,SqSearch(r,100,key));
printf("\n先进行快速排序使记录有序,快速排序后:\n");
quickSort(r,0,99);
print(r,100);
printf("二分查找:");
printf("%d的位置在:%3d\n\n",key,binarySearch(r,99,key));
return 0;
}
执行结果