概念:二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。
二分查找的前提是:(假设去查找一个数组)查找的数组是一个有序的数组。
实现思路:
- 1.确定循环结束条件就是左下标比右下标大,所以我们实在left<=right的条件下进行
- 2.分arr[mid]>target和arr[mid]<target两种条件
代码实现:
#include <stdio.h> int binarySort(int arr[],int target,int n){ int left=0; int right = n-1; int mid = left + (right-left)/2; while (left <= right) {
mid = left + (right-left)/2;
if (arr[mid] == target) {
return mid; } if (target < arr[mid]) { right = mid - 1; }else if (target > arr[mid] ){ left = mid+1; } } return -1; } int main(int argc, const char * argv[]) { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; printf("%d ===",binarySort(arr, 5, 10)); return 0; }