为什么我的冒泡排序算法实现对整个数组进行排序并跳过第一个索引? [英] Why is my bubble sort algorithm implementation sorting the entire array and skips the first index?

查看:98
本文介绍了为什么我的冒泡排序算法实现对整个数组进行排序并跳过第一个索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static int[] bubbleSort(int[] inputArray){

        for(int i = 0; i < inputArray.length  - 1; i++ ){

            int tempa = inputArray[i];
            int tempb = inputArray[i + 1];

            if(inputArray[i] > inputArray[i + 1]){
                inputArray[i] = tempb;
                inputArray[i + 1] = tempa;
                i = 0;
                System.out.println(Arrays.toString(inputArray));
            }
        }
        return inputArray;
}

此实现需要 [20、35,-15 ,7、55、1,-22] 并返回 [20,-22,-15、1、7、35、55]

推荐答案


为什么...跳过第一个索引?

Why ... skips the first index?

因为您在循环内设置了 i = 0 ,但随后循环将执行 i ++ ,因此仅在第一次迭代时检查第一个元素,而不在任何重新启动时检查。

Because you set i = 0 inside the loop, but then the loop will do i++, so the first element is only examined on the first iteration, not on any "restart".

To正确重新启动,请使用 i = -1 ,这样 i ++ 会使重新启动发生在 i = 0 ,而不是 i = 1

To restart correctly, use i = -1 so the i++ will make restart happen at i = 0, not at i = 1.

这将使代码正常工作,但是交换两个元素后立即重新启动效率不高,因为您将反复重新检查数组的开头。

That will make the code work, but it is inefficient to restart immediately upon swapping two elements, because you will repeatedly recheck the beginning of the array.

这篇关于为什么我的冒泡排序算法实现对整个数组进行排序并跳过第一个索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆