【发布时间】:2015-09-12 14:44:23
【问题描述】:
我在 Java 中创建了冒泡排序算法的实现。代码运行良好并给出了有效的输出,但是,由于某种原因,当我按升序对数据进行排序时,它做得很好,但是当我尝试打印出语句时出现问题。下面是我的代码,以及对问题的更好描述!
import java.util.Arrays;
import java.util.Scanner;
//import java.util.regex.Pattern;
//import java.util.stream.Stream;
public class BubbleSortNumeric {
public static void main (String [] args) {
Integer [] unsortedData = getDataInput();
Integer [] sortedDataAscending;
Integer [] sortedDataDescending;
long start = System.nanoTime();
sortedDataAscending = bubbleSortAscending(unsortedData);
sortedDataDescending = bubbleSortDescending(unsortedData);
long stop = System.nanoTime();
System.out.println("Ascending: " + Arrays.toString(sortedDataAscending));
System.out.println("Descening: " + Arrays.toString(sortedDataDescending));
System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");
}
private static Integer [] getDataInput() {
System.out.println("Enter a set of integers seperated by a space.");
Integer [] userInput = {};
String strInput;
try(Scanner sc = new Scanner(System.in)) {
strInput = sc.nextLine();
}
String [] inputData = strInput.split("\\s+");
try {
userInput = Arrays.asList(inputData).stream().map(Integer::valueOf).toArray(Integer[]::new);
}catch(NumberFormatException e) {
System.out.println("ERROR. Invalid input.\n" + e.getMessage());
}
return userInput;
}
private static Integer [] bubbleSortAscending(Integer[] ascendingUnsorted) {
int n = ascendingUnsorted.length;
System.out.println(n);
if(n == 1) {
return ascendingUnsorted;
}
boolean swapped;
int temp;
do {
swapped = false;
for(int i = 1; i < n; i++) {
if(ascendingUnsorted[i - 1] > ascendingUnsorted[i]) {
temp = ascendingUnsorted[i - 1];
ascendingUnsorted[i - 1] = ascendingUnsorted[i];
ascendingUnsorted[i] = temp;
swapped = true;
}
}
n--;
}while(swapped == true);
return ascendingUnsorted;
}
private static Integer [] bubbleSortDescending(Integer [] descendingUnsorted) {
int n = descendingUnsorted.length;
if(n == 1) {
return descendingUnsorted;
}
boolean swapped;
int temp;
do {
swapped = false;
for(int i = 1; i < n; i++) {
if(descendingUnsorted[i - 1] < descendingUnsorted[i]) {
temp = descendingUnsorted[i];
descendingUnsorted[i] = descendingUnsorted[i - 1];
descendingUnsorted[i - 1] = temp;
swapped = true;
}
}
n--;
}while(swapped == true);
return descendingUnsorted;
}
}
当我调用bubbleSortAscending 时,它工作正常,并按升序对数据进行排序。因为我正在计时程序的执行时间,所以我不想在对数据进行降序排序之前打印出结果。
我的问题是,虽然这两种方法都可以正常工作,但打印结果时出现问题。下面是一个例子:
输入
1 3 9 2 40 193
输出:
升序:[193, 40, 9, 3, 2, 1]
降序:[193,40,9,3,2,1]
执行时间:0.527142ms。
如果我将 print 语句移动到 sortedDataAscending = bubbleSortAscending(unsortedData); 行之后,那么它会给出正确的输出,但是,正如我已经说过的那样,我不希望这样。
所以我的问题是,即使我将结果分配给两个不同的变量,为什么当我打印两个变量的答案时,输出是一样的?
【问题讨论】:
-
在您的排序方法中,您实际上是对参数数组进行排序,因此您更改了作为参数给出的实际对象。
标签: java arrays sorting bubble-sort