Java初学者:数组冒泡排序

时间:2013-12-16 18:28:52

标签: java arrays sorting

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);

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

1 个答案:

答案 0 :(得分:1)

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

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。

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

请参阅此问题:Deep copy, shallow copy, clone

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