首页 > Java > java教程 > 正文

Java 数组排序并按表格形式输出

心靈之曲
发布: 2025-10-21 09:17:26
原创
1033人浏览过

java 数组排序并按表格形式输出

本文档旨在指导 Java 初学者如何对用户输入的测试分数进行排序,并以表格形式输出,同时保留原始输入的索引信息。我们将利用选择排序算法对分数进行排序,并调整输出方式,使其能够清晰地展示排序后的分数及其对应的原始输入序号,最终实现一个完整的排序输出表格。

问题分析

原有的代码存在一个问题,即 selectionSort 方法直接对 TestGrades 数组进行排序,导致输出时 grade number 和 grade value 对应错误。 期望的输出是:先按照用户输入的顺序输出 grade number 和 grade value,然后再输出一个排序后的 grade number 和 grade value,且 grade number 仍然是按照用户输入的顺序来的。

解决方案

核心思路是:

  1. 限制排序范围: selectionSort 方法只对用户实际输入的分数进行排序,而不是整个数组。
  2. 创建索引数组: 创建一个索引数组,用于存储原始数组的索引。在排序过程中,不直接交换分数,而是交换索引数组中的索引。
  3. 调整输出: 修改 OutputArray 方法,使其能够根据排序后的索引数组,输出排序后的分数及其对应的原始索引。

代码实现

以下是修改后的代码:

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

ReportPlus数据报表中心小程序
ReportPlus数据报表中心小程序

ReportPlust意在打造一套精美的数据报表模板,里面高度封装日历组件、表格组件、排行榜组件、条形进度条组件、文本块组件以及ucharts的多个图表组件,用户只需要按照虚拟数据的格式,传特定数据即可方便、快捷地打造出属于自己的报表页面。该小程序主要使用了ucharts和wyb-table两插件实现的数据报表功能。 特点使用的是uni-app中最受欢迎的图表uCharts插件完成图表展示,该插件

ReportPlus数据报表中心小程序 0
查看详情 ReportPlus数据报表中心小程序
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);

        // Sort and output sorted table
        ArrayIntro2T.sortAndOutputArray(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) {
            ScoreCount++;
            System.out.println("Enter the next test score or -1 to finish ");
            TestGrades[ScoreCount] = scan.nextInt();
        }
        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[] arr, int[] indices, int length) {
        for (int i = 0; i < length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < length; j++) {
                if (arr[indices[j]] < arr[indices[minIndex]]) {
                    minIndex = j;
                }
            }
            // Swap indices, not the values in arr
            int temp = indices[i];
            indices[i] = indices[minIndex];
            indices[minIndex] = temp;
        }
    }


    // 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);

    }

    public static void sortAndOutputArray(int[] TestGrades, int scoreCount) {
        // Create an array of indices
        int[] indices = new int[scoreCount];
        for (int i = 0; i < scoreCount; i++) {
            indices[i] = i;
        }

        // Sort the indices array based on the values in TestGrades
        selectionSort(TestGrades, indices, 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((indices[i] + 1) + "\t" + "\t" + "\t" + TestGrades[indices[i]]);
        }
    }
}
登录后复制

代码解释

  1. sortAndOutputArray 方法:

    • 接收 TestGrades 数组和 scoreCount 作为参数。
    • 创建一个 indices 数组,初始化为 [0, 1, 2, ..., scoreCount-1]。
    • 调用 selectionSort 方法,对 indices 数组进行排序,排序的依据是 TestGrades 数组中对应索引的值。
    • 循环遍历 indices 数组,根据排序后的索引,输出 TestGrades 数组中对应的值,以及原始的索引(indices[i] + 1)。
  2. selectionSort 方法:

    • 接收数组 arr,索引数组 indices 和数组有效长度 length 作为参数。
    • 在排序过程中,不直接交换 arr 数组中的元素,而是交换 indices 数组中的索引。
    • 比较大小时,使用 arr[indices[j]] 和 arr[indices[minIndex]],即比较 arr 数组中,索引数组 indices 对应的值。

运行结果

修改后的代码可以正确地对用户输入的测试分数进行排序,并以表格形式输出,同时保留原始输入的索引信息。 输出结果包含两个表格,第一个表格是按照用户输入的顺序输出的,第二个表格是按照分数大小排序后输出的。

注意事项

  • 代码中使用了选择排序算法,时间复杂度为 O(n^2)。对于大规模数据,可以考虑使用更高效的排序算法,例如归并排序或快速排序。
  • 代码中假设用户最多输入 25 个测试分数。如果需要支持更多数量的输入,需要修改数组的大小。
  • 代码中使用了 Scanner 类来读取用户输入。需要注意处理可能出现的输入异常,例如用户输入非数字字符。

总结

通过创建索引数组,并在排序过程中交换索引,可以实现在不改变原始数组顺序的情况下,对数组进行排序,并保留原始索引信息。 这种方法在需要同时访问排序后的数据和原始数据时非常有用。

以上就是Java 数组排序并按表格形式输出的详细内容,更多请关注php中文网其它相关文章!

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

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

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

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