0

我正在尝试编写一个程序,该程序生成一个由随机数填充的数组,然后对它们进行冒泡排序并将排序后的数组作为单独的数组返回,以便您可以比较两者。

但是,一旦我创建了我的随机数组,然后尝试创建另一个排序数组,排序数组“覆盖”随机数组,当我尝试打印它时,随机数组显示为排序数组。

我的问题是:如何修改我的代码,以便我可以创建随机双精度数组,然后生成另一个单独的数组,这是该随机数组的排序版本?

主要的:

import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;


public class BubbleMain {

public static void main(String args[])throws IOException{

    int n;
    Scanner keyboard = new Scanner(System.in);

    while(true){
        try{
            System.out.println("Enter the size of the array");
            n = keyboard.nextInt();

            if(n >= 2){
                break;
            }
            System.out.println("Size must be 2 or greater");
        }catch(InputMismatchException e){
            System.out.println("Value must be an integer");
            keyboard.nextLine();
        }
    }


    double[] template = new double[n];
    double[] mess = Bubble.randPop(template);

    double[] tidy = Bubble.bubbleSort(mess);


    Bubble.printOut(mess);
    Bubble.printOut(tidy);


}
}

泡泡类:

public class Bubble {

private double[] list;

public Bubble(double[] list){

    this.list = list;
}

public double[] getArray(){
    return list;
}

public static double[] randPop(double[] template){

    for(int i = 0; i < template.length; i++){
        template[i] = Math.random();
    }

    return template;
}



public static double[] bubbleSort(double[] mess){

    double[] tidy = new double[mess.length];

    for(int i=0; i<mess.length; i++)
    {
        for(int j=i + 1; j<mess.length; j++)
        {
            if(mess[i] > mess[j])
            {
                double temp = mess[i];
                mess[i] = mess[j];
                mess[j] = temp;
            }
        }
        tidy[i] = mess[i];
    }
    return tidy;
}




public static void printOut(double[] list){

    for(int i = 0; i < list.length; i++){
        System.out.println(list[i]);
    }
}

}
4

2 回答 2

1

只需先创建数组的副本:

public static double[] bubbleSort(double[] mess){
    // Copy the array    
    double[] tidy = Arrays.copyOf(mess, mess.length);

    // sort
    for(int i=0; i<tidy.length; i++)
    {
        for(int j=i + 1; j<tidy.length; j++)
        {
            if(tidy[i] > tidy[j])
            {
                double temp = tidy[i];
                tidy[i] = tidy[j];
                tidy[j] = temp;
            }
        }
    }
    return tidy;
}
于 2014-06-30T20:44:14.733 回答
0

bubbleSort中,您正在对mess数组进行排序,然后将其分配给tidy。所以 mess 会被排序,tidy 也会引用排序后的数组。

您需要将数组复制tidy

double[] tidy = Arrays.copyOf(mess, mess.length);

然后排序。

于 2014-06-30T20:46:56.590 回答