C语言二分法实现查找数组元素的方法:
递归算法
#include<stdio.h> //二分法实现数组查找 // int recurbinary(int *a, int key, int low, int high) { int mid; if(low > high) return -1; mid = (low + high)/2; if(a[mid] == key) return mid; else if(a[mid] > key) return recurbinary(a,key,low,mid -1); else return recurbinary(a,key,mid + 1,high); }
非递归算法
int binary( int *a, int key, int n ) { int left = 0, right = n - 1, mid = 0; mid = ( left + right ) / 2; while( left < right && a[mid] != key ) { if( a[mid] < key ) { left = mid + 1; } else if( a[mid] > key ) { right = mid - 1; } mid = ( left + right ) / 2; } if( a[mid] == key ) return mid; return -1; } int mAIn(void) { int a[10] = {2,4,6,8,10,12,14,16,18,20},t,k,f; scanf("%d",&t); k = recurbinary(a,t,2,20); f = binary(a,t,10); //非递归算法 if(k == -1){ printf("不存在此数\n"); }else{ printf("%-5d是数组第%d个元素\n%-5d数组的第%d个元素",k,k+1,f,f+1); } return 0; }