数据结构——折半查找
采用线性方式进行折半查找:
Binary_Search(int arr[],int key,int lowIndex,int upperIndex) { int middleIndex = 0; while(lowIndex <= upperIndex) { middleIndex = lowIndex + (upperIndex - lowIndex) / 2; if(arr[middleIndex] == key) { return middleIndex; } if (key > arr[middleIndex]) { lowIndex = middleIndex + 1; } else { upperIndex = middleIndex - 1; } } return -1; }
采用递归方式进行折半查找:
Binary_Search_Recursive(int arr[],int key,int lowIndex,int upperIndex) { if (lowIndex <= upperIndex) { int middleIndex = lowIndex + (upperIndex - lowIndex) / 2; if(arr[middleIndex] == key) { return middleIndex; } else if(arr[middleIndex] < key) { lowIndex = middleIndex + 1; Binary_Search_Recursive(arr,key,lowIndex,upperIndex); } else { upperIndex = middleIndex - 1; Binary_Search_Recursive(arr,key,lowIndex,upperIndex); } } else { return -1; } }