当前位置: 首页 > article >正文

JAVA学习-练习试用Java实现“选择排序”

问题:

用选择法对10个整数从小到大排序。
示例 :输入10个无序的数字,如4 85 3 234 45 345 345 122 30 12。输出排序好的10个整数,如

3
4
12
30
45
85
122
234
345
345。

解答思路:

以下是使用 Java 实现选择排序的代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int[] array = new int[10];

        System.out.println("请输入 10 个整数:");

        for (int i = 0; i < 10; i++) {
            array[i] = scanner.nextInt();
        }

        selectionSort(array);

        System.out.println("排序后的数组:");

        for (int num : array) {
            System.out.print(num + " ");
        }
    }

    public static void selectionSort(int[] array) {
        int n = array.length;

        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;

            for (int j = i + 1; j < n; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }

            if (minIndex!= i) {
                int temp = array[i];
                array[i] = array[minIndex];
                array[minIndex] = temp;
            }
        }
    }
}


上述代码中,首先定义了一个'selectionSort'方法,用于实现选择排序的逻辑。在'main'方法中,通过'Scanner'类获取用户输入的 10 个整数,并将它们存储在一个整数数组中。然后,调用'selectionSort'方法对数组进行排序。最后,遍历排序后的数组并打印输出。
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)


http://www.kler.cn/news/356005.html

相关文章:

  • 学生社会适应能力测试
  • 【最新华为OD机试E卷-支持在线评测】内存资源分配(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)
  • WordPress+Nginx 安装教程
  • 越狱你的 iPhone 安全吗?
  • JMeter之mqtt-jmeter 插件介绍
  • 一个使用接口模式、工厂模式、模板方法模式的日志文件系统
  • Python画笔案例-086 turtle 多线程绘画
  • Unity Vision Pro 保姆级开发教程-PolySpatial VisionOS Samples 示例场景
  • 基于STM32设计的实验室安全预警系统(OneNet)(246)
  • ssm医院交互系统+vue
  • 华为OD机试真题-数组连续和-2024年OD统一考试(E卷)
  • 无极低码课程【redis windows下服务注册密码修改】
  • 微信小程序-独立分包/分包预下载
  • Apache 出现 “403 forbidden“ 排查方法
  • rockscache源码分析:如何解决缓存db的最终一致性
  • nginx反向代理下的长连接
  • 小公司团队管理:8个你需要知道的要点
  • Ollama及其Open-WebUI部署更新
  • 【Linux】 exit 和 _exit 的区别
  • 【RV1126】板子adb 调试流程