gpt4 book ai didi

java - 如何在 Java 中循环选择排序?

转载 作者:行者123 更新时间:2023-11-30 08:13:31 27 4
gpt4 key购买 nike

我想显示选择排序的每次迭代以打印出它是如何工作的,我将如何循环并打印它?我让它在排序后打印输出。这是我的代码:

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;

}

}
}

最佳答案

您可以通过在选择排序的外循环末尾添加打印语句来实现。例如。 :

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();
}

关于java - 如何在 Java 中循环选择排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29934034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com