Java学习记录 排序并二分查找

2021-04-03 流程控制的逻辑训练任务 4

对数组{1,3,9,5,6,7,15,4,8}进行排序,然后使用二分查找元素 6 并输出排序后的下标。

 

代码如下:

public class Class5_4 {
    public static void main(String[] args) {
        //定义查找目标
        int target = 6;
        //定义数组
        int[] nums = {1,3,9,5,6,7,15,4};
        //调用排序方法
        sort(nums);
        //调用二分查找法
        find(nums,target);
    }
    //定义冒泡排序算法
    public static void sort(int[] nums){
        //第一层循环,循环数组长度-1轮
        for(int i = 0;i<nums.length-1;i++){
            //第二层循环
            for(int j = 0;j<nums.length-i-1;j++){
                if(nums[j]>nums[j+1]){
                    int temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
    }
    //定义二分查找算法
    public static void find(int[] nums,int target){
        int minIndex = 0;//最小下标
        int maxIndex = nums.length-1;//最大下标
        int centerIndex = (minIndex+maxIndex)/2;//中间下标
        while(true){
            if(target < nums[centerIndex]){
                //目标在中间下标的左边
                maxIndex = centerIndex-1;//移动最大下标
            }else if(target > nums[centerIndex]){
                //目标在中间下标的右边
                minIndex = centerIndex+1;//移动最小下标
            }else{
                //target == nums[centerIndex] 找到目标元素
                System.out.println("元素 "+ target + " 的下标是: " + centerIndex);
                break;
            }
            centerIndex = (minIndex+maxIndex)/2;//重新计算中间下标值
            if(minIndex>maxIndex){
                System.out.println(target+" 元素不存在");
                break;
            }
        }

    }
}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值