1 import java.util.Arrays; 2 import java.util.Scanner; 3 4 public class Array { 5 public static void main(String[] args) { 6 int[] arr = new int[10] ; 7 RandomAccessArray.randomAccessArray(arr,10);//调用自动生成有序数组的方法 8 //输入一个数 9 Scanner scan = new Scanner(System.in); 10 System.out.print("请输入一个0~100以内的整数: "); 11 int search = scan.nextInt(); 12 int index = binarySearchArray(arr, search); 13 14 } 15 public static int binarySearchArray(int[] arr ,int search){ 16 int startIndex =0,endIndex=arr.length; 17 18 int midIndex = (startIndex+endIndex)/2; 19 int mid = arr[midIndex]; 20 while(startIndex <= endIndex){
22 if (search > mid){ 23 startIndex = midIndex +1; 24 }else if (search < mid ){ 25 endIndex = midIndex -1; 26 }else{ 27 28 System.out.println("您要找的值"+search+"在数数列的下表为: "+ midIndex); 29 return midIndex; 30 }
32 if (startIndex > endIndex){ 33 System.out.println("您要查找的数不在数列中"); 34 } 35 } 36 return -1; 37 } 38 39 }
public static int binarySearchArray(int[] arr, int search)
{
int startIndex = 0, endIndex = arr.length;
int midIndex = (startIndex + endIndex) / 2;
int mid = arr[midIndex];
while (startIndex <= endIndex)
{
if (search > mid)
{
startIndex = midIndex + 1;
midIndex = (startIndex + endIndex) / 2;
mid = arr[midIndex];
}
else if (search < mid)
{
endIndex = midIndex - 1;
midIndex = (startIndex + endIndex) / 2;
mid = arr[midIndex];
}
else
{
System.out.println("您要找的值" + search + "在数数列的下表为: " + midIndex);
return midIndex;
}
if (startIndex > endIndex)
{
System.out.println("您要查找的数不在数列中");
}
}
return -1;
}
对不对 你在仔细看看,我没有测试,大概要这样放
这样子确实可以的,我自己优化下吧谢谢咯
public static int binarySearchArray(int[] arr ,int search){
int startIndex =0,endIndex=arr.length;
while(startIndex <= endIndex){
int midIndex = (startIndex+endIndex)/2;
int mid = arr[midIndex];
if (search > mid){
startIndex = midIndex +1;
}else if (search < mid ){
endIndex = midIndex -1;
}else{
System.out.println("您要找的值"+search+"在数数列的下表为: "+ midIndex);
return midIndex;
}
if (startIndex > endIndex){
System.out.println("您要查找的数不在数列中!");
}
}
return -1;
}
这样子就简洁多了。。
你这 mid 是不是需要变一下啊
How to change?
public static int binarySearchArray(int[] arr ,int search){
int startIndex =0,endIndex=arr.length;
while(startIndex <= endIndex){
int midIndex = (startIndex+endIndex)/2;
int mid = arr[midIndex];
if (search > mid){
startIndex = midIndex +1;
}else if (search < mid ){
endIndex = midIndex -1;
}else{
System.out.println("您要找的值"+search+"在数数列的下表为: "+ midIndex);
return midIndex;
}
if (startIndex > endIndex){
System.out.println("您要查找的数不在数列中!");
}
}
return -1;
}