我想显示选择排序的每个迭代以打印出它的工作方式,我将如何循环和打印它?我已经在排序后打印输出了。这是我的代码:
public class TestSelectionSort {
public static void main(String[] args) {
int list[] = { 2, 56, 34, 25, 73, 46, 89, 10, 5, 16 };
selectionSort(list, list.length);
System.out.println("After sorting, the list elements are:");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
}
public static void selectionSort(int[] list, int listLength) {
int index;
int smallestIndex;
int minIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
//Step a
smallestIndex = index;
for (minIndex = index + 1; minIndex < listLength; minIndex++)
if (list[minIndex] < list[smallestIndex])
smallestIndex = minIndex;
//Step b
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
}
}
答案 0 :(得分:2)
您可以通过在外部选择排序循环的末尾添加print语句来完成此操作。例如。 :
public static void selectionSort(int[] list, int listLength) {
int index;
int smallestIndex;
int minIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
//Step a
smallestIndex = index;
for (minIndex = index + 1; minIndex < listLength; minIndex++)
if (list[minIndex] < list[smallestIndex])
smallestIndex = minIndex;
//Step b
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
System.out.println("Printing data for iteration no " + index);
printData(list);
}
}
private static void printData(int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
}
答案 1 :(得分:1)
只需复制用于打印最终结果的代码段:
for(int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
在selectionSort()
。