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方法对数组进行排序。最后,我们打印排序后的数组。

相关推荐
KiddoStone8 分钟前
多实例schedule job同步数据流的数据一致性设计和实现方案
java
我爱C编程21 分钟前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生26 分钟前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器12329 分钟前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生29 分钟前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧30 分钟前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao30 分钟前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展
ゞ 正在缓冲99%…30 分钟前
leetcode67.二进制求和
算法·leetcode·位运算
YuTaoShao33 分钟前
【LeetCode 热题 100】240. 搜索二维矩阵 II——排除法
java·算法·leetcode
写个博客1 小时前
暑假算法日记第二天
算法