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 + " ");
        }
    }
}
相关推荐
兮动人4 分钟前
获取终端外网IP地址
java·网络·网络协议·tcp/ip·获取终端外网ip地址
呆呆的小鳄鱼5 分钟前
cin,cin.get()等异同点[面试题系列]
java·算法·面试
独立开阀者_FwtCoder15 分钟前
"页面白屏了?别慌!前端工程师必备的排查技巧和面试攻略"
java·前端·javascript
Touper.20 分钟前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun00770022 分钟前
std::forward作用
开发语言·c++·算法
静若繁花_jingjing37 分钟前
Redis线程模型
java·数据库·redis
JoernLee40 分钟前
机器学习算法:支持向量机SVM
人工智能·算法·机器学习
V我五十买鸡腿1 小时前
顺序栈和链式栈
c语言·数据结构·笔记·算法
hello早上好1 小时前
CGLIB代理核心原理
java·spring
魔镜魔镜_谁是世界上最漂亮的小仙女1 小时前
java-web开发
java·后端·架构