首页 > Java > java教程 > 正文

排序数组元素及其索引,并以表格形式输出

花韻仙語
发布: 2025-10-21 10:28:30
原创
134人浏览过

排序数组元素及其索引,并以表格形式输出

本文旨在提供一个完整的教程,指导读者如何使用Java程序对用户输入的测试分数进行排序,并以表格形式输出。核心内容包括:修改现有的选择排序算法,使其能够正确处理部分填充的数组;以及在不修改`main`方法的前提下,将排序后的测试分数以清晰的表格形式呈现。通过本文,读者将掌握数组排序、索引处理以及格式化输出等关键编程技巧。

问题分析与解决方案

原始代码存在的问题在于:

  1. 选择排序算法 selectionSort() 默认排序整个数组,而实际有效数据可能只占据数组的一部分。这导致未输入数据的数组位置(默认为0)也被排序,影响了最终的输出结果。
  2. 输出表格时,需要根据排序后的分数,正确地显示对应的原始“Grade Number”。

解决思路是:

  1. 修改 selectionSort() 方法,使其只排序有效数据部分。
  2. 创建一个新的方法,专门用于输出排序后的表格,并保留原始的索引信息。

修改选择排序算法

我们需要修改 selectionSort() 方法,使其只排序 TestGrades 数组中从索引 0 到 ScoreCount - 1 的元素。

public static void selectionSort(int[] TestGrades, int ScoreCount) {
    int startScan, index, minIndex, minValue;
    for (startScan = 0; startScan < (ScoreCount - 1); startScan++) {
        minIndex = startScan;
        minValue = TestGrades[startScan];
        for (index = startScan + 1; index < ScoreCount; index++) {
            if (TestGrades[index] < minValue) {
                minValue = TestGrades[index];
                minIndex = index;
            }
        }
        TestGrades[minIndex] = TestGrades[startScan];
        TestGrades[startScan] = minValue;
    }
}
登录后复制

关键在于将循环的边界条件从 TestGrades.length 修改为 ScoreCount,确保只对有效数据进行排序。

创建排序后表格输出方法

为了输出排序后的表格,我们需要创建一个新的方法,该方法接受 TestGrades 数组和 ScoreCount 作为输入,并输出排序后的分数及其对应的原始索引。

简篇AI排版
简篇AI排版

AI排版工具,上传图文素材,秒出专业效果!

简篇AI排版 554
查看详情 简篇AI排版
public static void OutputSortedArray(int[] TestGrades, int ScoreCount) {
    // 创建一个数组,保存原始索引
    Integer[] indices = new Integer[ScoreCount];
    for (int i = 0; i < ScoreCount; i++) {
        indices[i] = i;
    }

    // 使用 Lambda 表达式和 Comparator 对索引数组进行排序
    Arrays.sort(indices, (i1, i2) -> TestGrades[i1] - TestGrades[i2]);


    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]]);
    }
}
登录后复制

这个方法首先创建一个 indices 数组,用于存储原始索引。然后,使用 Arrays.sort 方法,结合 Lambda 表达式,根据 TestGrades 数组中的值对 indices 数组进行排序。排序后,indices 数组中的元素将按照对应的 TestGrades 数组中的值升序排列。最后,遍历排序后的 indices 数组,输出对应的原始索引和分数。

调用新方法

为了在不修改 main 方法的前提下调用新的排序方法,我们可以将调用代码添加到 OutputArray 方法的末尾。

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

    //调用排序方法和输出排序后数组的方法
    selectionSort(TestGrades, ScoreCount);
    OutputSortedArray(TestGrades, ScoreCount);
}
登录后复制

首先调用selectionSort方法,对数组进行排序。然后调用OutputSortedArray方法输出排序后的数组。

完整代码示例

import java.util.Arrays;
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);

    }

}

    //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[] TestGrades, int ScoreCount) {
            int startScan, index, minIndex, minValue;
            for (startScan = 0; startScan < (ScoreCount - 1); startScan++) {
                minIndex = startScan;
                minValue = TestGrades[startScan];
                for (index = startScan + 1; index < ScoreCount; index++) {
                    if (TestGrades[index] < minValue) {
                        minValue = TestGrades[index];
                        minIndex = index;
                    }
                }
                TestGrades[minIndex] = TestGrades[startScan];
                TestGrades[startScan] = minValue;
            }
        }

        public static void OutputSortedArray(int[] TestGrades, int ScoreCount) {
            // 创建一个数组,保存原始索引
            Integer[] indices = new Integer[ScoreCount];
            for (int i = 0; i < ScoreCount; i++) {
                indices[i] = i;
            }

            // 使用 Lambda 表达式和 Comparator 对索引数组进行排序
            Arrays.sort(indices, (i1, i2) -> TestGrades[i1] - TestGrades[i2]);


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

    //调用排序方法和输出排序后数组的方法
    selectionSort(TestGrades, ScoreCount);
    OutputSortedArray(TestGrades, ScoreCount);
}

    }
登录后复制

注意事项与总结

  • 数组边界检查: 在处理数组时,务必注意数组的边界,避免出现 ArrayIndexOutOfBoundsException 异常。
  • 代码可读性 编写清晰、简洁的代码,添加适当的注释,有助于提高代码的可读性和可维护性。
  • 性能优化: 对于大规模数据的排序,可以考虑使用更高效的排序算法,例如归并排序或快速排序。
  • 原始索引保存: 在排序过程中,使用索引数组的方式可以有效地保留原始数据的索引信息,这在很多实际应用中非常有用。

通过本教程,你已经学会了如何修改选择排序算法,使其能够正确处理部分填充的数组,并以表格形式输出排序后的分数及其对应的原始索引。这些技巧在处理类似的数据排序和展示问题时非常有用。

以上就是排序数组元素及其索引,并以表格形式输出的详细内容,更多请关注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号