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

相关推荐
阿里技术7 小时前
Agent 评测:方法论与体系设计
大数据·人工智能·算法
Sylvia33.7 小时前
足球数据接口开发实战:如何用火星数据API盘活赛事应用
java·服务器·开发语言·数据库·python
小小放舟、7 小时前
PaiCLI-Demo:从零实现 ReAct Agent + Tool Call
java·后端·intellij-idea·springboot·agent·react·tool call
cxr8287 小时前
大语言模型上下文缓存命中率测试全场景清单
人工智能·python·算法·缓存·语言模型·自然语言处理·llm
noipp8 小时前
推荐题目:洛谷 P13554 【MX-X15-T1】奶龙龙
c语言·数据结构·c++·算法·编程·洛谷
念风8 小时前
一阶低通滤波器系数的两种计算方法
算法
geovindu8 小时前
go: Enumeration Algorithm
开发语言·后端·算法·golang·枚举算法
退休倒计时8 小时前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
C++、Java和Python的菜鸟9 小时前
第2章 前端Web基础(js、vue+Ajax)
java
harmful_sheep9 小时前
idea相关设置
java·ide·intellij-idea