[英]Return a bubble sort as a separate array
我正在尝试编写一个程序,该程序生成一个由随机数组成的数组,然后对它们进行冒泡排序,然后将排序后的数组作为一个单独的数组返回,以便您可以比较两者。
但是,一旦我创建了随机数组,然后尝试创建另一个排序数组,排序数组就会“覆盖”随机数组,而当我尝试将其打印时,随机数组将显示为排序数组。
我的问题是:如何修改代码,以便创建随机双精度数和数组,然后生成另一个独立的数组,即该随机数的排序版本?
主要:
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]);
}
}
}
只需先创建数组的副本:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.