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 + " ");
        }
    }
}
相关推荐
言乐63 分钟前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
NiceCloud喜云26 分钟前
Anthropic 一周三连发:Cowork 多端、Fable 5 按需付费、J-space 论文的技术解读
java·服务器·网络·人工智能·ai
凉云生烟28 分钟前
机器学习 02- KNN算法
人工智能·算法·机器学习
wabs66630 分钟前
关于动态规划【力扣583.两个字符串的删除操作的思考】
算法·leetcode·动态规划
SamDeepThinking34 分钟前
组合还是继承?我在项目里主要看这两个判断
java·后端·面试
可编程芯片开发37 分钟前
空气流量和空气压力参数解耦系统simulink建模与仿真
算法
momo43 分钟前
JAVA基础知识
java·开发语言
_Doubletful1 小时前
妙用位运算:解构汉明距离至100%(提供分析与多解)
c语言·算法·leetcode
凯瑟琳.奥古斯特1 小时前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展
Keven_111 小时前
AcWing算法提高课思路速查:搜索
算法·搜索