JAVA二分数组搜索法,程序举例
package JAVA_Project_01_04;
import java.util.Arrays;
public class TextArraySearch {
public static int binarySearch1(int[] array, int index, int beginIndex, int endIndex) {
int mindIndex = (beginIndex + endIndex) / 2;
if (index < array[beginIndex] | index > array[endIndex] || beginIndex > endIndex)
return -1;
if (index < array[mindIndex]) {
return binarySearch1(array, index, beginIndex, mindIndex - 1);
} else if (index>array[mindIndex]) {
return binarySearch1(array, index, mindIndex + 1, endIndex);
}else {
return mindIndex;
}
}
public static int binarySearch2(int[] array, int index) {
int beginIndex = 0;
int endIndex = array.length - 1;
int midIndex = -1;
if (index < array[beginIndex] || index > array[endIndex] || beginIndex > endIndex)
return -1;
while (beginIndex <= endIndex) {
midIndex = (beginIndex + endIndex) / 2;
if (index < array[midIndex]) {
endIndex = midIndex - 1;
} else if (index > array[midIndex]) {
beginIndex = midIndex + 1;
} else {
return midIndex;
}
}
return -1;
}
public static void main(String[] args) {
int[]array=new int[]{12,3,2,18,24,15,20};
int number=18;
int num=1;
Arrays.sort(array);
System.out.println("元素"+number+"所在的位置为:"+binarySearch1(array,number,0,array.length-1));
System.out.println("元素"+number+"所在的位置为:"+binarySearch2(array,number));
System.out.println("元素"+num+"所在的位置为:"+binarySearch2(array,num));
}
}