我应该采用一个数字数组:{51, 63, 48, 98, 75, 63, 92, 30, 32, 32, 36, 89, 4, 76, 73, 90, 64, 99, 36, 96} 并将它们从低到高排序,然后从高到低排序。
当我尝试从最高到最低打印时,它会使第一个输出相同。有人看到我的代码中有任何错误吗?
package l7c14sort;
import java.util.Arrays;
public class L7C14Sort {
public static void main(String a[]){
int[] arr1 = {51, 63, 48, 98, 75, 63, 92, 30, 32, 32, 36, 89, 4, 76, 73, 90, 64, 99, 36, 96};
int[] arr2 = doInsertionSort(arr1);
int[] arr3 = doInsertionSortAgain(arr1);
System.out.println("Original input: "+Arrays.toString(arr1)+"\n");
System.out.println("Lowest to highest:\n");
for(int i:arr2)
{
System.out.print(i);
System.out.print(", ");
}
System.out.println("\n\n");
System.out.println("Highest to lowest:\n");
for(int k:arr3)
{
System.out.print(k);
System.out.print(", ");
}
System.out.println("\n");
}
public static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
public static int[] doInsertionSortAgain(int[] input2){
int temp2;
for (int k = 1; k < input2.length; k++) {
for(int j = k ; j > 0 ; j--){
if(input2[j] > input2[j-1]){
temp2 = input2[j];
input2[j] = input2[j-1];
input2[j-1] = temp2;
}
}
}
return input2;
}
}
输出:
Original input: [99, 98, 96, 92, 90, 89, 76, 75, 73, 64, 63, 63, 51,
48, 36, 36, 32, 32, 30, 4]
从最高到最低:
99, 98, 96, 92, 90, 89, 76, 75, 73, 64, 63, 63, 51, 48, 36, 36, 32, 32, 30, 4,
从最低到最高:
4,30,32,32,36,36,48,51,63,63,64,73,75,76,89,90,92,96,98,99
最佳答案
好消息:您的算法运行良好。
在 Java 中,数组是通过引用传递的,而不是通过值传递的。这意味着当您设置 int[] arr2 = doInsertionSort(arr1);
时,数组 arr2
将被设置为 doInsertionSort
的结果code> 方法,在排序后返回其 input
参数。基本上,arr1
、arr2
、arr3
、input
和input2
都指向完全相同的数组。
您有两个简单的选项来解决正在打印的问题:
重构
main()
以便使用一个数组:打印其内容,从低到高排序,再次打印其内容,从高到低排序,然后再次打印其内容。 (如果这是类(class)作业,这可能就是您的讲师打算让您做的事情。)复制要操作的
input
参数。您可以使用 System.arraycopy() 来执行此操作,如下所示:int[] myArray; System.arraycopy(input, 0, myArray, 0, input.length );
然后,对于选项 2,您需要编辑方法以在每次使用
input
时使用myArray
而不是input
.
请注意,您不需要调用变量 input2
、temp2
等。就像 i
、 j
和 k
超出范围并在 for
循环结束后被遗忘,您的变量 input
和 temp
在您声明它们的 block 之外没有任何意义。
希望这有帮助!
关于java - 使用插入排序对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713916/