首页 > 代码库 > 二分法

二分法

import java.util.*;
class Demo12
{
 public static void main(String[] args)
 {
  int[] arr = {6, 10, 12, 23, 45, 56, 78, 89};
  int num;
  int sum;
  
  System.out.println("请输入要查找的数");
  Scanner scanner = new Scanner(System.in);
  num = scanner.nextInt();
  sum = findNum(arr, num);
  System.out.println("该数存在且元素索引值是 " + sum);
 }
 
 public static int findNum(int[] arr, int num)
 {
  int max = arr.length - 1;
  int min = 0;
  int mid = (max + min) / 2;
  while(true)
  {
   if(num > arr[mid])
   {
    min = mid + 1;
   }
   else if (num == arr[mid])
   {
    return mid;
   }
   else
   {
    max = mid - 1;
   }
   
   if(min > max)
   {
    mid = -1;
    return mid;
   }
   mid = (max + min)/2;
  }
  
  
 }
 
}

二分法