数组_经典排序算法

数组_经典排序算法
  1. 选择排序
  • i ~ n-1 范围上,找到最小值并放在 i 位置,然后 i+1 ~ n-1 范围上继续
  1. 冒泡排序
  • 0 ~ i 范围上,相邻位置较大的数滚下去,最大值最终来到 i 位置,然后 0 ~ i-1 范围上继续
  1. 插入排序
  • 0 ~ i 范围上已经有序,新来的数从右到左滑到不再小的位置上插入,然后继续

接下来,会用具体代码实现以上三种排序算法,并包含一个具体实例:

  1. 选择排序 (Selection Sort)
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 static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        selectionSort(arr);
        System.out.println("Selection Sorted array: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}
  1. 冒泡排序 (Bubble Sort)
public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 交换 arr[j] 和 arr[j+1]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        bubbleSort(arr);
        System.out.println("Bubble Sorted array: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}
  1. 插入排序 (Insertion Sort)
public class InsertionSort {
    public static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;

            // 将 arr[i] 插入到已排序部分
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6};
        insertionSort(arr);
        System.out.println("Insertion Sorted array: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值