乱数が入力された配列を生成し、それらをバブルソートし、ソートされた配列を別の配列として返すプログラムを作成して、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]);
}
}
}