我有一个包含用户输入的数组。该程序是关于冒泡排序,选择排序和插入排序。第一次冒泡,第二次选择,然后插入排序。
我无法解决问题。当代码进入选择排序时,数组已经按冒泡排序排序。
我首先尝试制作2个临时数组,以使用"源数组"在选择和插入排序,但那些数组通过冒泡排序再次排序。 (我不明白为什么)
有没有办法单独对我的数组进行排序,或者我必须让它们成为方法?我也在计算互换和比较BTW。谢谢!
System.out.println("• Please enter the number of elements in the Sorting Bag:");
length = input.nextInt();
System.out.println("• The number of elements: " + length);
int[] SorBag = new int[length];
int[] SorBag2 = new int[length];
int[] SorBag3 = new int[length];
System.out.println("• Please enter the elements of Sorting Bag:");
for (int i = 0; i < SorBag.length ; i++) {
SorBag[i] = input.nextInt();
}
SorBag2 = SorBag;
SorBag3 = SorBag;
System.out.print("• Elements in the Sorting Bag are:");
for (int j = 0; j < SorBag.length; j++) {
System.out.print(" " + SorBag[j]);
}
System.out.println("");
System.out.println("");
//Bubble Sort
for (int i = 1; i < SorBag.length; i++) {
for (int j = 0; j < SorBag.length - i; j++) {
BComparison++;
if (SorBag[j] > SorBag[j + 1]) {
BSwaps++;
temp1 = SorBag[j + 1];
SorBag[j + 1] = SorBag[j];
SorBag[j] = temp1;
}
}
}
System.out.print("• Bubble Sort:");
for (int k = 0; k < SorBag.length; k++) {
System.out.print(" " + SorBag[k] + " ");
}
System.out.print("Comparisons: " + BComparison + " Swaps: " + BSwaps);
System.out.println(" ");
//Selection Sort
for (int i = 0; i < SorBag2.length; i++) {
min = i;
for (int j = i + 1; j < SorBag2.length; j++) {
SComparison++;
if (SorBag2[j] < SorBag2[min]) {
min = j;
}
if (min != i) {
temp2 = SorBag2[i];
SorBag2[i] = SorBag2[min];
SorBag2[min] = temp2;
SSwaps++;
}
}
}
System.out.print("• Selection Sort:");
for (int k = 0; k < SorBag2.length; k++) {
System.out.print(" " + SorBag2[k] + " ");
}
System.out.print("Comparisons: " + SComparison + " Swaps: " + SSwaps);
System.out.println(" ");
//Insertion Sort
for (int i = 1; i < SorBag3.length; i++) {
int j = 0;
while (j > i && SorBag3[j] < SorBag3[j - 1]) {
temp3 = SorBag3[j];
SorBag3[j] = SorBag3[j - 1];
SorBag3[j - 1] = temp3;
ISwaps++;
j--;
}
IComparison++;
}
System.out.print("• Insertion Sort:");
for (int k = 0; k < SorBag3.length; k++) {
System.out.print(" " + SorBag3[k] + " ");
}
System.out.print("Comparisons: " + IComparison + " Swaps: " + ISwaps);
System.out.println(" ");
}
}
答案 0 :(得分:4)
SorBag2 = SorBag
和SorBag3 = SorBag
将SorBag
的引用复制到其他两个数组,而不是仅复制数据。所以而不是:
System.out.println("• Please enter the elements of Sorting Bag:");
for (int i = 0; i < SorBag.length ; i++) {
SorBag[i] = input.nextInt();
}
SorBag2 = SorBag;
SorBag3 = SorBag;
试试这个:
System.out.println("• Please enter the elements of Sorting Bag:");
for (int i = 0; i < SorBag.length ; i++) {
int nextInt = intput.nextInt();
SorBag[i] = nextInt;
SorBag2[i] = nextInt;
SorBag3[i] = nextInt;
}