好吧,所以我尝试在我的代码中实现冒泡排序算法,但现在我的第二个数组的输出(在我的代码中)给了我很多零。任何人都可以告诉我我的代码有什么问题以及我如何修复它以便删除零并且我的第二个数组的输出中唯一剩下的是数字固定的吗?
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
scan.close();
}
}
}
答案 0 :(得分:1)
在排序前将array1
复制到正确长度的array2
,例如
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
}
array1[i] = input;
}
int[] array2 = Arrays.copyOfRange(array1, 0, i);
System.out.println("Before sorting: " + Arrays.toString(array2));
Arrays.sort(array2); // <-- How I would sort.
System.out.println("After sorting: " + Arrays.toString(array2));
这是必要的,因为i
可能不是 10,在这种情况下,您的数组包含0
(s)来填充其他位置。
是否可以使用for-loop将我的所有数字从数组1移动到数组2?
是。您可以使用for
循环
private static int[] copyOfRange(int[] arr, int start, int end) {
int pos = 0;
int[] out = new int[end - start];
for (int i = start; i < end; i++) {
out[pos] = arr[i];
pos++;
}
return out;
}
内置版几乎肯定更好。
答案 1 :(得分:1)
1)你正在多次打印数组,我想你可能会给0作为输入,这就是你到处看到0的原因。
2)您已经创建了不必要的array2。
将打印逻辑移出for循环,如下面的代码段所示。否则你的逻辑看起来很好,除了错误的print语句循环。
public static void main(String args[]) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
scan.close();
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
}