[AppleScript] 纯文本查看 复制代码
package array;
/*
* 例题:
* 给定一个有序的数组,如果往该数组中存储一个元素,并保证这个数组还是有序的,
* 那么这个元素的存储的角标为如何获取。
* {13,15,19,28,33,45,78,106};
*
*/
public class HalfSearch {
public static void main(String[] args) {
int[] arr={13,15,19,28,33,45,78,106};
int index=myBinarySearch(arr,44);
System.out.println(index);
}
//Arrays里有binarySearch()方法用于二分查找,这里我自定了一个二分查找方法
public static int myBinarySearch(int[] arr,int key ){
int start,mid,end;
start=0;
end=arr.length-1;
mid=(start+end)/2;
while(start<=end){
if(key>arr[mid])
start=mid+1;
else if(key<arr[mid]){
end=mid-1;
}
else
return mid;
mid=(start+end)/2;
}
return mid+1;
}
}
[Java] 纯文本查看 复制代码
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo_test01 {
public static void main(String[] args) {
int key = 20;
Integer[] arr = {13,15,19,28,33,45,78,106};
List<Integer> list = Arrays.asList(arr);
int binarySearch = Collections.binarySearch(list, key);
int abs = Math.abs(binarySearch+1);
System.out.printf("插入点角标为%d\n", abs);
}
}