选择排序(Selection Sort)

选择排序(Selection Sort)

简介

选择排序(Selection Sort)是一种简单直观的排序算法,每次从未排序部分选择最小(或最大)的元素放置到已排序部分的末尾。

算法步骤

选择排序算法的步骤如下:

  1. 从未排序部分选择最小(或最大)的元素。
  2. 将选中的元素与未排序部分的第一个元素交换位置。
  3. 标记该元素为已排序部分的末尾。
  4. 重复步骤1-3,直到所有元素都被排序。

示例代码

下面是使用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;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            // 交换最小元素和当前位置的元素
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }
}

// 示例用法
public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 1, 3};
        SelectionSort.selectionSort(arr);
        System.out.println("排序结果:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
在上述代码中,我们定义了一个SelectionSort类和一个Main类。SelectionSort类中的selectionSort函数接受一个整数数组作为参数,并使用嵌套的循环来实现选择排序。在Main类中,我们创建一个示例数组,调用SelectionSort.selectionSort方法对数组进行排序,并打印排序结果。

示例演示
下面是一个示例演示选择排序算法的执行过程:

初始数组:[5, 2, 8, 1, 3]

第一轮选择:[1, 2, 8, 5, 3]
第二轮选择:[1, 2, 8, 5, 3]
第三轮选择:[1, 2, 3, 5, 8]
第四轮选择:[1, 2, 3, 5, 8]

排序完成:[1, 2, 3, 5, 8]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值