java创建一个整型数组,数组的大小由用户输入?
(1)对该数组进行随机赋值,取值范围[2000,8000];
(2)对该数组进行排序;
(3)采用二分法查询查询,目标值由用户输入; 展开
希望对你有帮助,对了,记得采纳哟
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入数组的大小:");
int capacity = scanner.nextInt();
Integer[] array = new Integer[capacity];
for (int i = 0; i <array.length ; i++) {
array[i] = (int)(Math.random()*(6000+1))+1999;
}
//排序 升
Arrays.sort(array);
System.out.println("生成数组:"+Arrays.toString(array));
System.out.println("输入要查询的数:");
int target = scanner.nextInt();
int ret = biSearch(array,target);
System.out.println("查找到的位置:"+ret);
}
//二分查找
public static int biSearch(Integer[] array, int t){
int lo = 0;
int ro = array.length-1;
int mid;
while (lo <= ro){
mid = (lo + ro)/2;
if (array[mid] == t){
return mid + 1;
}else if(array[mid] < t){
//往右找
lo = mid + 1;
}else if (array[mid] > t){
//往左找
ro = mid - 1;
}
}
return -1;
}
运行效果: