0

乱数が入力された配列を生成し、それらをバブルソートし、ソートされた配列を別の配列として返すプログラムを作成して、2 つを比較できるようにしようとしています。

ただし、ランダム配列を作成してから別のソート済み配列を作成しようとすると、ソート済み配列がランダム配列を「上書き」し、印刷しようとするとランダム配列がソート済み配列として表示されます。

私の質問は次のとおりです。コードを変更して、ランダムな double の配列を作成し、そのランダムな配列のソートされたバージョンである別の別の配列を生成するにはどうすればよいですか?

主要:

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 に答える