折半查找法,每次都是去找最中间的数,前提是这个数组必须是有序的,从小到大
JAVA实现
C语言实现public static void main(String[] args) { int []arr={1,2,3,4,5,6,7,8}; System.out.println(find_index(arr,3)); System.out.println(find_index(arr,8)); System.out.println(find_index(arr,9)); } /** * 二分查找的实现 * @param arr * @param num * @return */ public static int find_index(int []arr,int num){ int left=0;//定义左边界 int right=arr.length-1;//定义右边界 while (left<=right){ int mid=(left+right)/2; if (num>arr[mid]){ left=mid+1; } else if (num
#include
#define N 100 int main()//二分法前提查找的数据是有序的 { int arr[N] = { 0 }; for (int i = 0; i < N; i++) { arr[i] = i; } int n=0; scanf("%d", &n); int right = 99; int left = 0; while (left<=right) { int mid = (right + left) / 2; if (arr[mid] == n) { printf("找到了,下标是%d", mid); break; } if (arr[mid]>n) { right = mid-1; } if (arr[mid] right){printf("该数字不存在");} return 0; }
二分查找的递归模式注意点:查找的的终止条件很重要,终止条件是<=,而不能是<
public static void main(String[] args) { int []arr={1,2,3,4,5,6}; System.out.println(find_index(arr,3)); System.out.println(find_index(arr,6)); System.out.println(find_index(arr,9)); } /** * 二分查找的实现 * @param arr * @param num * @return */ public static int find_index(int []arr,int num){ int left=0;//定义左边界 int right=arr.length-1;//定义右边界 while (left
arr[mid]){ left=mid+1; } else if (num 我们发现6是存在的,但是没有找到,因为left
public static void main(String[] args) { int []arr={1,2,3,4,5,6}; System.out.println(findIndexRecursion(arr,3,0,arr.length-1)); } public static int findIndexRecursion(int arr[],int num,int left,int right){ //终止条件 当left>right 说明找不到 if (left>right){ System.out.println("没有找到该元素"); return -1; } int mid=(left+right)/2; if (arr[mid]==num){//说明找到了 System.out.println("找到了下标为"+mid); return mid; } else if (arr[mid]>num){//说明只需要原本区间的左区间 findIndexRecursion(arr,num,left,mid-1); } else {//只需要原本区间的右区间 findIndexRecursion(arr,num,mid-1,right); } return 1; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)