java - 为什么我的选择排序程序没有给出最后几个数字的正确输出?
问题描述
我一直在学习这个 MOOC.fi Java 课程,并遇到了关于在这个页面上开发选择排序算法的问题(https://java-programming.mooc.fi/part-7/2-algorithms)。我没有解决方案,所以我想知道这里是否有人可以帮助我解决这个问题。基本上,我完成了第 4 部分之前的所有步骤,但是当我尝试使用选择排序方法时,我的方法只能正确排序数字,直到它到达倒数第二个数字,然后它开始错误地切换数字。谁能查看我的代码并告诉我哪里出错了?
import java.util.Arrays;
public class MainProgram {
public static void main(String[] args) {
// Testing methods
// Test Part 1
int[] numbers = {6, 5, 8, 7, 11};
System.out.println("Smallest: " + MainProgram.smallest(numbers));
// Testing Part 2
System.out.println("Index of the smallest number: " + MainProgram.indexOfSmallest(numbers));
// Testing Part 3
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 0));
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 1));
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 2));
// Testing Part 4
int[] numbers2 = {3, 2, 5, 4, 8};
System.out.println(Arrays.toString(numbers2));
MainProgram.swap(numbers2, 1, 0);
System.out.println(Arrays.toString(numbers2));
MainProgram.swap(numbers2, 0, 3);
System.out.println(Arrays.toString(numbers2));
// Testing Part 5
int[] numbers3 = {8, 3, 7, 9, 1, 2, 4};
MainProgram.sort(numbers3);
}
// Part 1
public static int smallest(int[] array) {
int smallest = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
return smallest;
}
// Part 2
public static int indexOfSmallest(int[] array){
int smallest = array[0];
int i;
int finalIndex = 0;
for (i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
finalIndex = i;
}
}
return finalIndex;
}
// Part 3
public static int indexOfSmallestFrom(int[] table, int startIndex) {
int smallest = table[startIndex];
int i = startIndex;
int finalIndex = 0;
for (i = startIndex; i < table.length; i++) {
if (table[i] < smallest) {
smallest = table[i];
finalIndex = i;
}
}
return finalIndex;
}
// Part 4
public static void swap(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
// Part 5
public static void sort(int[] array) {
int smallestIndex;
for (int i = 0; i < array.length; i++) {
smallestIndex = indexOfSmallestFrom(array, i);
swap(array, smallestIndex, i);
System.out.println(Arrays.toString(array));
}
}
}
这是错误的输出:
[1, 3, 7, 9, 8, 2, 4]
[1, 2, 7, 9, 8, 3, 4]
[1, 2, 3, 9, 8, 7, 4]
[1, 2, 3, 4, 8, 7, 9]
[1, 2, 3, 4, 7, 8, 9]
[8, 2, 3, 4, 7, 1, 9]
[9, 2, 3, 4, 7, 1, 8]
解决方案
在 3 块中,您设置
finalIndex = 0
;
它应该设置为 startIndex
推荐阅读
- java - 将文本中的数据加载到不同的字符串中
- javascript - 在 Bluebird 的承诺上使用 await 返回 undefined
- python - 如何在 Python 的 for 循环中更改索引的值?
- mysql - mysql 未在 XAMPP LINUX MINT 18.3 中启动
- c - 如何在函数中使用 realloc 创建结构的动态数组
- javascript - 使用 ECMAScript 6 箭头函数作为类方法
- npm - 我正在尝试在 npm 上创建我的第一个模块,但 npm 给出错误
- python - python中python中的while循环上的多个或条件
- r - 汽车包装中的散点图()格式
- html - CSS 字体在 Mozilla Firefox、Microsoft Edge 和 Opera 上不起作用