gpt4 book ai didi

java - 这个选择排序代码有什么问题?

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

我被要求做一个选择排序算法,但它不起作用,我也不知道为什么。这是代码:

    int count = 0;
int count2;
int min;
int size = scan.nextInt();
int temp = 0;
int[] numbers = new int[size];

while (count < size) {
numbers[count] = scan.nextInt();
count ++;
}
count = 0;
while (count < size) {
count2 = size;
min = numbers[count];
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) {
min = count2;
}
}
temp = numbers[temp];
numbers[temp] = numbers[count];
numbers[count] = temp;
count ++;
}

count = 0;
while (count < size) {
System.out.println(numbers[count]);
count ++;
}
}

输入:101个02个93个8个4个75个6

输出:1个2个98个3个3个8个4个74

最佳答案

在 while 循环中,您尝试使用 numbers[0] 元素作为 numbers[] numbers[min] 的索引

min = numbers[count]; \\min is value of first element of numbers[]
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) { \\ you try to use value of numbers[0] element as index of numbers[] aray.
min = count2;
}

如果 (numbers[count2] < numbers[min]) 则替换如果 (numbers[count2] < min)

关于java - 这个选择排序代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18851896/

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