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

相关推荐
mikuyyds7 小时前
geo-toolbox 水文插件算法解析:从 Muskingum 到 Muskingum-Cunge
算法·rust·gis
白远山7 小时前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析
码兄科技8 小时前
24小时自助健身房系统软件开发实战指南:功能设计与部署方案
java·spring boot·uni-app
Omics Pro8 小时前
斯坦福Nature+Science|广义虚拟细胞基础大模型
数据库·人工智能·算法·机器学习·自然语言处理
程序猿_极客8 小时前
【免费】分享一套优质的基于SpringBoot的扶贫助农管理系统(详解)
java·springboot·课程设计·计算机项目
代数狂人8 小时前
机器学习数学基础──从零开始 导读
人工智能·算法
2603_965148118 小时前
AI+API选品:下一代智能商务助手雏形已现
java·大数据·数据库·人工智能·数据挖掘
wuminyu8 小时前
HotSpot的轻量锁与膨胀后的ObjectMonitor状态重建原理
java·linux·c语言·jvm·c++
CoderYanger8 小时前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法