0

0

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

碧海醫心

碧海醫心

发布时间:2025-10-21 12:56:01

|

702人浏览过

|

来源于php中文网

原创

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

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

问题分析

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

解决方案

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

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

代码实现

以下是修改后的代码:

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

灵云AI开放平台
灵云AI开放平台

灵云AI开放平台

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

代码解释:

  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 数组和排序算法解决实际问题。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1051

2023.08.02

int占多少字节
int占多少字节

int占4个字节,意味着一个int变量可以存储范围在-2,147,483,648到2,147,483,647之间的整数值,在某些情况下也可能是2个字节或8个字节,int是一种常用的数据类型,用于表示整数,需要根据具体情况选择合适的数据类型,以确保程序的正确性和性能。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

616

2024.08.29

c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

335

2025.08.29

C++中int的含义
C++中int的含义

本专题整合了C++中int相关内容,阅读专题下面的文章了解更多详细内容。

235

2025.08.29

页面置换算法
页面置换算法

页面置换算法是操作系统中用来决定在内存中哪些页面应该被换出以便为新的页面提供空间的算法。本专题为大家提供页面置换算法的相关文章,大家可以免费体验。

503

2023.08.14

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

69

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

109

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

326

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

62

2026.03.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.4万人学习

C# 教程
C# 教程

共94课时 | 11.4万人学习

Java 教程
Java 教程

共578课时 | 82.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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