【问题标题】:Bubble sort swap method clarification冒泡排序交换方法说明
【发布时间】:2021-07-09 22:53:51
【问题描述】:

我一直在学习关于冒泡排序的课程,但是交换方法实现的一部分一直困扰着我。对我来说没有意义并希望有人能澄清的部分与关于索引的比较有关。

public static void main(String[] args) {
        int[] intArray = {20, 35, -15, 7, 55, 1, -22};

       //start at index 6 which is -22 value; as long as the length of the array is more than 0; decrement down to the first index
        for (int lastUnsortedIndex = intArray.length -1; lastUnsortedIndex > 0; lastUnsortedIndex -- ){

           //i=0; as long as i is less than length of intArray -1, so 6; i++
            for(int i =0; i< lastUnsortedIndex; i++){
                //if value at index i is more than value at index i+1
                if(intArray[i] > intArray[i +1]){
                    //swap their positions
                    swap(intArray, i , i+1);
                }
            }
        }
        for(int num : intArray){
            System.out.println(num);
        }
    }
    //for swapping
    public static void swap (int[] array , int i , int j){
        System.out.println("i= "+i);
        System.out.println("j= "+j);

        if(i == j){ // if they are the same then just return
            return;
        }
        int temp = array[i];// need the temporary variable to hold value at position i because
        //... we are going to swap array[i] with j, but still need to retain the value so we can assign it to array[j]
        array[i] = array[j];
        array[j] = temp;

    }

如您所见,if(i == j){return;} 似乎只是在我没有记错的情况下比较索引。为什么还要费心做这个检查?除非我在这里遗漏了什么,否则我似乎永远不会等于 i+1?

【问题讨论】:

  • Why even bother doing this check? 这是一个小优化。如果 i == j,那么它是同一个对象,显然不需要交换。
  • 虽然我会质疑它是否真的“高效”。交换本身只是交换两个整数(Java 没有复制构造函数,也永远不会复制堆内存,除非你非常努力地工作)。所以进行比较和分支实际上可能会使代码变慢。
  • 我怎么可能等于 j? J 设置为 i +1
  • @JessicaJones 你是对的。在您发布的代码中,检查i==j 是不必要的,因为冒泡排序永远不会尝试与自身交换元素。一个可能是 Fisher-Yates shuffle 的算法示例。因此,如果这只是您的专家用于所有事情的通用可重用 swap 函数,那么它是可以理解的。但是作为markspace already said,它可能会使代码变慢,即使对于ij 可能相等的代码也是如此。
  • @WJS YAGNI,杰西卡琼斯是对的,这在这里没有意义

标签: java algorithm sorting bubble-sort


【解决方案1】:

没有理由进行检查。将i+1 传递给swap 也是没有意义的。只需传递i,并在任何地方将j 替换为i+1。不要担心检查是否相等。如果您关心速度,请删除打印语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    相关资源
    最近更新 更多