gpt4 book ai didi

java - 选择排序不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:45:06 25 4
gpt4 key购买 nike

<分区>

这是我使用 Java 1.7 实现的选择排序:

public class SelectionSort {

private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

public static int[] sort(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++) {
int smallestValue = i;
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[j] < numbers[smallestValue])
smallestValue = j;
}
swap(numbers, smallestValue, i);
}
return numbers;
}
}

在我的测试工具中,以下代码用于调用排序方法:

public static void main(String args[]) {    
int[] unsortedNumbers = new int[] { 9, 8, 5, 4, 3, 7, 2, 1 };
int[] sortedNumbers = new int[0];

System.out.println("\nUnsorted Numbers:");
if (unsortedNumbers.length >= 1) {
System.out.print(unsortedNumbers[0]);
}

for (int i=1; i <unsortedNumbers.length; i++) {
System.out.print(", " + unsortedNumbers[i]);
}

sortedNumbers = SelectionSort.sort(unsortedNumbers);

System.out.println("\n\nSorted Numbers:");

if (sortedNumbers.length >= 1) {
System.out.print(sortedNumbers[0]);
}

for (int j=1; j < sortedNumbers.length; j++) {
System.out.print(", " + sortedNumbers.length);
}

这是非常令人沮丧/错误的输出:

Unsorted Numbers:
9, 8, 5, 4, 3, 7, 2, 1

Sorted Numbers:
1, 8, 8, 8, 8, 8, 8, 8

我可能做错了什么?

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