Java实现选择排序及其动图演示

选择排序是一种简单直观的排序算法。它的基本思想是每次从未排序的元素中选出最小(或最大)的元素,然后将其放到已排序的序列的末尾。具体步骤如下:

  1. 首先,找到未排序序列中的最小(或最大)元素,记录其位置。
  2. 将最小(或最大)元素与未排序序列的第一个元素交换位置,将最小(或最大)元素放到已排序序列的末尾。
  3. 重复以上步骤,直到所有元素都排序完成。

选择排序的时间复杂度是O(n^2),其中n是待排序序列的长度。虽然选择排序的时间复杂度较高,但是它的实现比较简单,且不需要额外的空间,所以在一些简单的应用场景中仍然是一种常用的排序算法。

以下是Java代码实现选择排序的示例:

java 复制代码
public class SelectionSort {
    public static void selectionSort(int[] arr) {
        int n = arr.length;
        
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            
            // Find the index of the minimum element in the unsorted part of the array
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            
            // Swap the minimum element with the first element of the unsorted part
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};

        selectionSort(arr);

        System.out.println("Sorted array: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

在main方法中,我们创建了一个整数数组来进行排序。然后调用selectionSort方法对数组进行排序。最后,我们打印排序后的数组。

相关推荐
rannn_1115 分钟前
JVM 垃圾回收面试题全解析:从基础到进阶
java·开发语言·jvm·后端·面试
Wang's Blog11 分钟前
Java框架 SpringCloud 快速入门: Ribbon 饥饿加载
java·spring cloud·ribbon
Omics Pro17 分钟前
反式感知虚拟细胞!超越线性序列
数据库·人工智能·算法·机器学习·自然语言处理
-dzk-20 分钟前
【动态规划】LC 152.乘积最大子数组
算法·动态规划
积流成海22 分钟前
一致性哈希原理与实现:分布式系统负载均衡
算法·负载均衡·哈希算法·哈希函数·盘子工具站
天空鸟_时光不老34 分钟前
10-Agent安全隐患与SQL执行层加固
java·数据库·人工智能·sql·spring·maven·mybatis
Nebula_g2 小时前
JavaSE加强:IO流
java·开发语言·windows·stream·javase
rannn_1112 小时前
JVM 面试题:类加载过程详解(附高频考点)
java·jvm·后端
程序猿乐锅6 小时前
从0-1一文详解RabbitMQ
java·分布式·后端·中间件·rabbitmq·ruby
考虑考虑9 小时前
JDK26中的List.ofLazy()
java·后端·java ee