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 + " ");
        }
    }
}
相关推荐
gumichef2 分钟前
二叉树_堆
算法
Liangwei Lin13 分钟前
LeetCode 70. 爬楼梯
算法
霑潇雨17 分钟前
Spark学习基础转换算子案例(单词计数(WordCount))
java·大数据·分布式·学习·spark·maven
夏日听雨眠26 分钟前
Linux(信号,管道,共享内存)
java·服务器·网络
TANGLONG22226 分钟前
【C++】继承详解——基类/派生类、作用域、默认函数、菱形继承(超详细)
java·c语言·c++·经验分享·笔记·ajax
洛水水32 分钟前
【力扣100题】38.路径总和 III
算法·leetcode·深度优先
zmsofts34 分钟前
IntelliJ IDEA)因为内存不足而崩溃
java·ide·intellij-idea
小侯不躺平.38 分钟前
C++ Boost库【2】 --stringalgo字符串算法
linux·c++·算法
Dlrb121141 分钟前
C语言-字符串指针与函数指针
java·c语言·前端
萝卜白菜。1 小时前
通过cmdline-jmxclient.jar采集TongWeb8.0监控值
java·jar