1,二分查找:
- int Find(int arr[], int key,int length)
- {
- assert(arr!=NULL&&length>0);
- int low=0,high=length,mid;
- while(low<=high)
- {
- mid=(low+high)/2;
- if(arr[mid]==key) return mid;
- else
- {
- if(arr[mid]>key) high=mid-1;
- else low=mid+1;
- }
- }
- return-1;
- }
假定集合中油重复的元素,找到某个数首次出现的位置
- int find(int * arr , int length, int key){
- int low = 0,high = length-1,mid;
- while(low <= high){
- mid = (low + high)/2;
- if (arr[mid] < key){
- low = mid + 1;
- }else if(arr[mid] > key){
- high = mid - 1;
- }else{
- if (mid == 0) return mid;
- if (mid >= 1 && arr[mid-1] != key) return mid;
- else high = mid - 1;
- }
- }
- return -1;
- }