weixin_71093833 2022-07-16 21:12 采纳率: 100%
浏览 36
已结题

二分法排序(循环不执行)

img


如上是我写的代码,是一个二分法查找数组里面的元素的,但是不知道为什么它就是不执行我这个循环,而是直接跳过,请大家帮忙指正一下。

  • 写回答

2条回答 默认 最新

  • piaoyiren 2022-07-16 21:21
    关注
    
    public class BinarySort {
    
    public static void binarySort(int[] source) {
    
    int i, j;
    
    int high, low, mid;
    
    int temp;
    
    for (i = 1; i < source.length; i++) {
    
    // 查找区上界
    
    low = 0;
    
    // 查找区下界
    
    high = i - 1;
    
    //将当前待插入记录保存在临时变量中
    
    temp = source[i];
    
    while (low <= high) {
    
    // 找出中间值
    
    // mid = (low + high) / 2;
    
    mid = (low + high) >> 1;
    
    //如果待插入记录比中间记录小
    
    if (temp
    
    // 插入点在低半区
    
    high = mid - 1;
    
    } else {
    
    // 插入点在高半区
    
    low = mid + 1;
    
    }
    
    }
    
    //将前面所有大于当前待插入记录的记录后移
    
    for (j = i - 1; j >=low; j--) {
    
    source[j + 1] = source[j];
    
    }
    
    //将待插入记录回填到正确位置.
    
    source[low] = temp;
    
    System.out.print("第" + i + "趟排序:");
    
    printArray(source);
    
    }
    
    }
    
    private static void printArray(int[] source) {
    
    for (int i = 0; i < source.length; i++) {
    
    System.out.print("\t" + source[i]);
    
    }
    
    System.out.println();
    
    }
    
    public static void main(String[] args) {
    
    int source[] = new int[] { 12, 15, 9, 14, 4, 18, 23, 6 };
    
    System.out.print("初始关键字:");
    
    printArray(source);
    
    System.out.println("");
    
    binarySort(source);
    
    System.out.print("\n\n排序后结果:");
    
    printArray(source);
    
    }
    
    }
    
    
    ————————————————
    版权声明:本文为CSDN博主「weixin_39885683」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/weixin_39885683/article/details/114064175
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月24日
  • 已采纳回答 7月16日
  • 创建了问题 7月16日

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染