这个世界并不在乎你的自尊,只在乎你做出来的成绩,然后再去强调你的感受。——比尔盖茨
关键字:递归、有序数组、二分查找流程图奉上源码
package Binary_Search;
import java.util.Scanner;
public class Binary_Search
{
public static int binarySearch(int[] list, int low, int high, int key)
{
if(list==null)
{
return -1;
}
int middle = (low high)/2;
if(low<=high)
{
if(list[middle]==key)
{
return middle;
}
else if(list[low]<=list[high])
{
if(list[middle]<key)
{
return binarySearch(list,middle 1,high,key);
}
else
{
return binarySearch(list,low,middle-1,key);
}
}
else
{
if(list[middle]<key)
{
return binarySearch(list,low,middle-1,key);
}
else
{
return binarySearch(list,middle 1,high,key);
}
}
}
return -1;
}
public static void main(String[] args)
{
int[]a= {9,8,3,2,1,0};
int i;
System.out.println("请输入要查找的数字;");
Scanner in =new Scanner(System.in);
int key=in.nextInt();
int subscript=binarySearch(a,0,a.length-1,key);
if(subscript==-1)
System.out.println("数组中无此数,查找失败");
else
System.out.println("该数的下标是:" subscript);
}
}
温馨提示小伙伴可以用for循环
测一下验证代码的正确性
Jachyn
专注生活
● 与你分享 IT|数学|英语|摄影 小知识 ●