对数组{1,3,9,5,6,7,15,4,8}进行排序,然后使用二分查找元素 6 并输出排序后的下标。
package Object;
public class shuck_4 {
public static void main(String[] args) {
//首先,先给数组进行排序 冒泡排序
int[] nums ={1,3,9,5,6,7,15,4,8};
//定义一个temp值
int temp;
//外层循环控制的是:比较的轮数
//内层循环次数:length-1
for(int i = 0; i<nums.length;i++){
//内层循环控制的是:每次比较的轮数
//第i轮(i从0开始计算),比较次数为:length-i-1
for(int j = 0;j<nums.length-i-1;i++){
if(nums[j]>nums[j+1]){
//两两相比,满足移动条件
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
//要查找的数据
int num = 6;
//关键的三个变量
//1. 最小下标
int minIndex = 0;
//2. 最大下标
int maxIndex = nums.length-1;
//3.中间下标
int centerIndex = (minIndex+maxIndex)/2;
while(true){
if(nums[centerIndex]>num){
//中间下标大,最大下标-1
maxIndex = centerIndex-1;
}else if(nums[centerIndex]<num){
//中间下标小,最小下标+1
minIndex = centerIndex+1;
}else{
//找到了数据位置
break;
}
if(minIndex>maxIndex){
centerIndex = -1;
}
//当边界发生变化,需要更新中间下标
centerIndex = (minIndex+maxIndex)/2;
}
System.out.println(centerIndex);
}
}