You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的选择排序算法存在什么问题?Java实现代码无法完成排序

修复你的Java选择排序代码

嘿,我来帮你排查选择排序的问题~先看你代码里几个关键的错误点,再给你修正后的完整实现:

问题分析

  • 外层循环终止条件错误:你写的 for(y=0;y<a.length-2;y++) 会少遍历一次数组,导致最后一个元素无法被正确排序。选择排序的外层循环只需要遍历到倒数第二个元素(索引为 a.length-2),所以终止条件应该是 y < a.length - 1。
  • selectionsort2 方法不完整:这个方法的核心作用是从指定起始索引开始,找到数组中最小元素的索引,但你只写了参数开头,缺失了关键逻辑。
  • 类成员变量 y 没必要:把 y 定义成类成员容易引发意外问题,直接在方法里定义局部变量更安全。
  • 类名不符合Java规范:Java类名应该采用大驼峰命名,selectionsort 建议改成 SelectionSort。

修正后的完整代码

import java.util.Arrays;

// 类名改成大驼峰规范
public class SelectionSort {
    // 交换方法没问题,保留
    void swap(int a[], int firstIndex, int secondIndex) {
        int temp = a[firstIndex];
        a[firstIndex] = a[secondIndex];
        a[secondIndex] = temp;
    }

    // 选择排序的主方法,这里把y改成局部变量
    public void selectionSort(int a[]) {
        int lowestIndex;
        // 外层循环修正终止条件
        for (int y = 0; y < a.length - 1; y++) {
            lowestIndex = findLowestIndex(a, y);
            swap(a, y, lowestIndex);
        }
    }

    // 补全找最小索引的方法,参数是数组和起始索引
    public int findLowestIndex(int a[], int startIndex) {
        int lowestIndex = startIndex;
        // 从起始索引的下一个元素开始遍历
        for (int i = startIndex + 1; i < a.length; i++) {
            if (a[i] < a[lowestIndex]) {
                lowestIndex = i;
            }
        }
        return lowestIndex;
    }

    // 测试用的主方法
    public static void main(String[] args) {
        SelectionSort sorter = new SelectionSort();
        int[] arr = {5, 2, 9, 1, 5, 6};
        System.out.println("排序前: " + Arrays.toString(arr));
        sorter.selectionSort(arr);
        System.out.println("排序后: " + Arrays.toString(arr));
    }
}

关键修正说明

  1. 外层循环:y < a.length - 1 确保我们遍历到倒数第二个元素,因为最后一个元素会在前面的元素都排好后自动处于正确位置。
  2. findLowestIndex 方法:从 startIndex 开始遍历数组,逐一比较元素大小,记录最小元素的索引,这是选择排序的核心步骤——找到当前未排序部分的最小值。
  3. 局部变量替代类成员:把 y 定义在 selectionSort 方法内部,避免其他方法修改这个变量导致的逻辑错误。

运行上面的代码,就能正确对数组进行排序啦~

内容的提问来源于stack exchange,提问作者Akash Bisht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:41:14