二分查找
#include <stdio.h> #include <string.h> typedef struct { int hash; char data[20]; } D; int search(int* nums, int numsSize, int target) { int left=0; int right=numsSize; int mid; while(left<right){ mid=(right+left)/2; if(nums[mid]==target){return mid;} else if(nums[mid]<target){left=mid+1;} else if(nums[mid]>target){right=mid;} } return -1; } int searchB(D *d, int size, D target){ int left = 0; int right = size; int mid; int i; while(left<right){ mid = (right+left)/2; if(d[mid].hash == target.hash){ if(0==strcmp(d[mid].data,target.data)){return mid;} for(left=1;d[mid-left].hash == target.hash;left++){ if(0==strcmp(d[mid-left].data,target.data)){return mid-left;} } for(right=1;d[mid+right].hash == target.hash;right++){ if(0==strcmp(d[mid+right].data,target.data)){return mid+right;} } return -1; } else if(d[mid].hash<target.hash){left=mid+1;} else if(d[mid].hash>target.hash){right=mid;} } return -1; } int main() { D d[10]; int i; for (i=0;i<10;i++) { d[i].hash=i; sprintf(d[i].data,"PPPPP %d",i); } d[7].hash = 6; d[8].hash = 6; d[5].hash = 6; for (i=0;i<10;i++) { printf("%d -> %d\t%s\n",i,d[i].hash,d[i].data); } D f = {6,"PPPPP 8"}; int r = searchB(d,10,f); printf("r = %d\n",r); return 0; }