Java 初学者:数组气泡排序



main 方法创建一个随机整数数组,然后调用升序和降序方法来对数组进行排序。似乎当我调用升序和降序方法时,它会改变原始数组的值。打印时收到的输出是三个数组,全部按降序排序。

public static void main(String[] args){
    Random random = new Random();
    Scanner myScan = new Scanner(System.in);
    System.out.println("How many random numbers should be created?");
    int size = myScan.nextInt();
    int[] array = new int[size];
    for(int i = 0; i<array.length; i++){    
        array[i] = random.nextInt(256);
    }
    int[] ascending = BubbleSort.ascending(array);
    int[] descending = BubbleSort.descending(array);
    System.out.print("Original array: ");
    for(int i = 0; i< array.length; i++){
        System.out.print(array[i] + " ");
    }
    System.out.println();   
    System.out.print("Array in ascending order: ");
    for(int i =0; i< ascending.length; i++){
        System.out.print(ascending[i] + " ");
    }
    System.out.println();

    System.out.print("Array in descending order: ");
    for(int i = 0; i<descending.length; i++){
        System.out.print(descending[i] + " ");
    }
    System.out.println();
}

以下是两种排序方法。

public static int[] ascending(int[] a){
    int temp;
    for(int i = 0; i < a.length - 1; i++){
        for(int j = 0; j < a.length - 1; j++){
            if(a[j] > a[j+1]){
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
    }
    return(a);
}
public static int[] descending(int[] b){
    int temp;
    for(int i = 0; i < b.length - 1; i++){
        for(int j = 0; j < b.length -1; j++){   
            if(b[j] < b[j+1]){
                temp = b[j];
                b[j] = b[j+1];
                b[j+1] = temp;
            }
        }
    }
    return(b);
}

而不是

int[] ascending = BubbleSort.ascending(array);

我想试试

int[] ascending = new int[array.length];
ascending = BubbleSort.ascending(array);

但我收到了相同的结果。很抱歉成为这样的编程新手,并感谢您的任何指导!

我没有看过你的排序的正确性,但我可以告诉你的是,这两种方法都接受一个数组并直接修改它。

public static int[] descending(int[] b){
    int temp;
    for(int i = 0; i < b.length - 1; i++){
        for(int j = 0; j < b.length -1; j++){   
            if(b[j] < b[j+1]){
                temp = b[j];
                // both of these calls CHANGE the array
                b[j] = b[j+1];                     
                b[j+1] = temp;
            }
        }
    }
    return(b);
}

接受数组 (b( 并返回排序后的数组(返回 b(。 这意味着您传递到此函数中的任何数组都将被更改。

 int[] array = new int[size];

因此,该数组将传递到:

int[] ascending = BubbleSort.ascending(array);
int[] descending = BubbleSort.descending(array);
首先创建get,然后通过升序修改

一次,然后通过降序修改AGAIn。

为了避免这种情况,您需要做的是创建此数组的副本,或者以不影响原始数组的方式执行排序。

请参阅此问题: 深拷贝、浅拷贝、克隆

有关 Java 中的复制、深度复制和克隆的讨论。 这应该可以澄清您遇到的一些问题。

最新更新