首页 > Java > java教程 > 正文

Java 数组排序与索引输出教程

碧海醫心
发布: 2025-10-21 12:56:01
原创
684人浏览过

java 数组排序与索引输出教程

本文旨在指导 Java 初学者如何对数组中的元素进行排序,并按照特定的表格格式输出排序后的结果,同时保持原始索引信息的对应关系。通过修改现有的代码,我们将实现一个额外的输出,以展示按升序排列的测试分数,并保留它们在原始输入中的索引位置。

问题分析

原始代码存在的问题在于,排序算法 selectionSort() 对整个数组进行排序,包括未使用的数组元素。这导致输出结果中包含大量的 0,并且索引信息没有正确保留。我们需要修改代码,使其仅对用户输入的有效分数进行排序,并输出排序后的分数及其对应的原始索引。

解决方案

我们可以通过以下步骤解决问题:

  1. 修改 selectionSort() 方法: 使其只对 TestGrades 数组中前 ScoreCount 个元素进行排序。
  2. 创建索引数组: 创建一个新的数组 indices,用于存储 TestGrades 数组中每个元素的原始索引。
  3. 修改排序逻辑: 在 selectionSort() 方法中,同时交换 TestGrades 数组和 indices 数组中的元素,以保持索引信息的对应关系。
  4. 添加输出方法: 创建一个新的方法 OutputSortedArray(),用于输出排序后的测试分数及其对应的原始索引。

代码实现

以下是修改后的代码:

立即学习Java免费学习笔记(深入)”;

import java.util.Scanner;

public class ArrayIntro2 {

    public static void main(String[] args) {
        //integer array
        int[] TestGrades = new int[25];

        //creating object of ArrayIntro2T
        ArrayIntro2T pass = new ArrayIntro2T(TestGrades, 0, 0, 0);

        //getting total and filling array
        int scoreCount = ArrayIntro2T.FillArray(TestGrades, 0);

        //get average score
        double avg = pass.ComputeAverage(TestGrades, scoreCount);

        //outputting table
        ArrayIntro2T.OutputArray(TestGrades, scoreCount, avg);

        // Outputting sorted table
        ArrayIntro2T.selectionSort(TestGrades, scoreCount); // Sort only valid scores
        ArrayIntro2T.OutputSortedArray(TestGrades, scoreCount);
    }
}

//new class to store methods
class ArrayIntro2T {
    //variable declaration

    double CalcAvg = 0;
    int ScoreTotal = 0;
    int ScoreCount = 0;
    int[] TestGrades = new int[25];


    //constructor
    public ArrayIntro2T(int[] TestGradesT, int ScoreCountT, double CalcAvgT, int ScoreTotalT) {
        TestGrades = TestGradesT;
        ScoreCount = ScoreCountT;
        CalcAvg = CalcAvgT;
        ScoreTotal = ScoreTotalT;
    }

    //method to fill array
    public static int FillArray(int[] TestGrades, int ScoreCount) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter test scores one at a time, up to 25 values or enter -1 to quit");
        TestGrades[ScoreCount] = scan.nextInt();

        if (TestGrades[ScoreCount] == -1) {
            System.out.println("You have chosen to quit ");
        }

        while (TestGrades[ScoreCount] >= 0 && ScoreCount < 25) { // Corrected the loop condition
            ScoreCount++;
            if (ScoreCount < 25) { // Added check to prevent ArrayIndexOutOfBoundsException
                System.out.println("Enter the next test score or -1 to finish ");
                TestGrades[ScoreCount] = scan.nextInt();
            } else {
                System.out.println("Maximum number of scores reached.");
                break;
            }
        }
        return ScoreCount;
    }

    //method to compute average
    public double ComputeAverage(int[] TestGrades, int ScoreCount) {

        for (int i = 0; i < ScoreCount; i++) {
            ScoreTotal += TestGrades[i];
            CalcAvg = (double) ScoreTotal / (double) ScoreCount;
        }

        return CalcAvg;

    }

    public static void selectionSort(int[] TestGrades, int scoreCount) {
        int startScan, index, minIndex, minValue;
        int[] indices = new int[scoreCount];
        for (int i = 0; i < scoreCount; i++) {
            indices[i] = i; // Initialize indices array
        }

        for (startScan = 0; startScan < (scoreCount - 1); startScan++) {
            minIndex = startScan;
            minValue = TestGrades[indices[startScan]]; // Use indices array for comparison
            for (index = startScan + 1; index < scoreCount; index++) {
                if (TestGrades[indices[index]] < minValue) { // Use indices array for comparison
                    minValue = TestGrades[indices[index]];
                    minIndex = index;
                }
            }
            // Swap both TestGrades and indices
            int temp = indices[startScan];
            indices[startScan] = indices[minIndex];
            indices[minIndex] = temp;
        }
        // Reorder TestGrades based on sorted indices
        int[] sortedGrades = new int[scoreCount];
        for (int i = 0; i < scoreCount; i++) {
            sortedGrades[i] = TestGrades[indices[i]];
        }
        // Copy the sorted grades back to TestGrades array
        System.arraycopy(sortedGrades, 0, TestGrades, 0, scoreCount);
    }

    //method to output scores and average
    public static void OutputArray(int[] TestGrades, int ScoreCount, double CalcAvg) {

        System.out.println("Grade Number\t\tGrade Value");

        for (int i = 0; i < ScoreCount; i++) {
            System.out.println((i + 1) + "\t" + "\t" + "\t" + TestGrades[i]);
        }

        System.out.printf("Calculated Average\t" + "%.2f%%\n", CalcAvg); // Added newline for better formatting
    }

    public static void OutputSortedArray(int[] TestGrades, int scoreCount) {
        System.out.println("\nTable of sorted test scores");
        System.out.println("Grade Number\t\tGrade Value");
        for (int i = 0; i < scoreCount; i++) {
            System.out.println((i + 1) + "\t" + "\t" + "\t" + TestGrades[i]);
        }
    }
}
登录后复制

代码解释:

纳米搜索
纳米搜索

纳米搜索:360推出的新一代AI搜索引擎

纳米搜索30
查看详情 纳米搜索
  1. selectionSort(int[] TestGrades, int scoreCount):

    • 接受数组 TestGrades 和有效分数数量 scoreCount 作为参数。
    • 创建 indices 数组,初始化为 0 到 scoreCount-1,表示原始索引。
    • 修改排序逻辑,使用 indices 数组间接访问 TestGrades 中的元素进行比较。
    • 交换 indices 数组中的元素,以保持索引信息的对应关系。
    • 创建一个新的数组sortedGrades,用来存储排序后的数组,然后将排序后的数组拷贝到原数组中。
  2. OutputSortedArray(int[] TestGrades, int scoreCount):

    • 接受数组 TestGrades 和有效分数数量 scoreCount 作为参数。
    • 按照表格格式输出排序后的测试分数及其对应的原始索引。

注意事项

  • 确保 ScoreCount 的值正确,避免数组越界异常。
  • 在 FillArray() 方法中,需要检查 ScoreCount 的值,防止超出数组的最大长度。
  • 该代码使用了选择排序算法,时间复杂度为 O(n^2)。对于大型数组,可以考虑使用更高效的排序算法,例如归并排序或快速排序。

总结

通过修改 selectionSort() 方法并添加 OutputSortedArray() 方法,我们成功地实现了对数组中有效元素的排序,并按照特定的表格格式输出排序后的结果,同时保持了原始索引信息的对应关系。这个例子展示了如何使用 Java 数组和排序算法解决实际问题。

以上就是Java 数组排序与索引输出教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号