折半查找、选择排序在一位数组中的应用
1 #include<stdio.h> 2 #define N 10 3 int main(void) 4 { 5 void select_sort(int *a); 6 void arry_print(int *a); 7 void search(int *a,int n); 8 9 int i,number; 10 int a[N]; 11 printf("Enter matrix:\n"); 12 for(i=0;i<N;i++) 13 scanf("%d",&a[i]); 14 printf("Before sort:\n"); 15 arry_print(a); 16 printf("After sort:\n"); 17 select_sort(a); 18 arry_print(a); 19 printf("Enter the number you look for:\n"); 20 scanf("%d",&number); 21 search(a,number); 22 return 0; 23 } 24 void select_sort(int *a) 25 { 26 int i,j,min,t; 27 for(i=0;i<N-1;i++) 28 { 29 min=i; 30 for(j=i+1;j<N;j++) 31 if(a[min]>a[j]) 32 min=j; 33 if(min!=i) 34 { 35 36 t=a[i]; 37 38 a[i]=a[min]; 39 40 a[min]=t; 41 42 } 43 } 44 } 45 void arry_print(int *a) 46 { 47 for(int i=0;i<N;i++) 48 printf("%d\t",a[i]); 49 } 50 void search(int *a,int n) 51 { 52 int top=0,bott=N-1,mid; 53 int i,j,k,loca,flag=0; 54 if(n<a[0]||n>a[N-1]) 55 printf("Cannot find %d.\n",n); 56 while((!flag)&&(top<=bott)) 57 { 58 mid=(top+bott)/2; 59 if(n==a[mid]) 60 { 61 loca=mid; 62 printf("Has found %d,it positon is %d .\n",n,loca+1); 63 flag=1; 64 } 65 else if(n<a[mid]) 66 bott=mid-1; 67 else 68 top=mid+1; 69 } 70 }