Java中集中常见的算法

以下是对选择排序、冒泡排序和插入排序的理解及代码实现

选择排序

理解:它通过不断地从待排序元素中选择最小(或最大)元素,并将其放置在已排序序列的一端。

代码实现:

复制代码
public class SelectionSort {
    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            if (minIndex!= i) {
                int temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6};
        selectionSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

冒泡排序

理解:它通过反复比较相邻元素并交换位置,将最大的元素逐步"冒泡"到数组末尾。

复制代码
public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (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);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

插入排序

理解:它逐个将元素插入已排序的部分,以达到排序的目的。

复制代码
public class InsertionSort {
    public static void insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];
            int j = i - 1;

            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);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
相关推荐
小冷coding6 分钟前
【面试】结合项目整理的场景面试题,覆盖 Java 基础、锁、多线程、数据库、分布式锁 / 事务、消息中间件等核心维度
java·数据库·面试
鬼先生_sir6 分钟前
SpringCloud-GateWay网关
java·spring cloud·gateway
sinat_2869451918 分钟前
harness engineering
人工智能·算法·chatgpt
卓怡学长20 分钟前
m319个人网站的设计与实现
java·数据库·spring·tomcat·maven·intellij-idea
少许极端29 分钟前
算法奇妙屋(四十三)-贪心算法学习之路10
学习·算法·贪心算法
Zzj_tju35 分钟前
Java 从入门到精通(十二):File 与 IO 流基础,为什么程序“读写文件”时总是容易出问题?
java·python·php
算法鑫探1 小时前
10个数下标排序:最大值、最小值与平均值(下)
c语言·数据结构·算法·排序算法·新人首发
样例过了就是过了1 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
IronMurphy1 小时前
【算法三十七】51. N 皇后
算法·深度优先
DoUfp0bgq1 小时前
从直觉到算法:贝叶斯思维的技术底层与工程实现
算法