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

相关推荐
Navigator_Z3 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
小蒜学长3 小时前
微信小程序-高校自习室管理系统(代码+数据库+LW)
java·spring boot·后端·微信小程序·自习室管理
Nil2083 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年3 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
鸥梨菌Honevid3 小时前
UVM 中 REQ 和 RSP 类型详解:从通信模型到 item_done 与 put_response
java·前端·servlet
瑞克-桑切斯3 小时前
真实企业场景 运维安全与管理
java·网络·github
牧羊人.3333 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
Nil2084 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
老板一杯拿铁4 小时前
Java 八股文面试详解:从基础到进阶的全面梳理
java·面试
const_qiu4 小时前
第 2.5 章 2.5.4-2.5.5:JWT 双 Token 与声明式权限守卫
java·人工智能