【发布时间】:2017-04-06 06:42:04
【问题描述】:
这是我的代码:
import java.util.Scanner;
public class BubbleSort{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int[] array = new int[5];
for(int i = 0; i < array.length; i++){
System.out.println("Enter value: ");
array[i] = sc.nextInt();
}
int temp;
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = array[j];
}
}
}
System.out.print("Sorted Array: ");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
当我输入一个数组时。输出是:
Enter value:
5
Enter value:
4
Enter value:
3
Enter value:
2
Enter value:
1
Sorted Array: 1 1 1 1 1
【问题讨论】:
-
检查你的交换逻辑。你在哪里设置
temp? -
将
array[j + 1] = array[j];更改为array[j + 1] = temp; -
这个问题的标题很好。
标签: java arrays algorithm sorting bubble-sort