Java排序算法-持续更新中

news2025/4/19 12:43:55

paixusuanfa

一、比较排序

1.1 交换排序

数组两元素交换位置

public class ArrayUtil {

    /**
     * 交换数组中的两个元素
     * @param array 数组
     * @param ele1Idx 元素1的索引下标
     * @param ele2Idx 元素1的索引下表
     */
    public static void swap(int[] array, int ele1Idx, int ele2Idx) {
        int tmp = array[ele1Idx];
        array[ele1Idx] = array[ele2Idx];
        array[ele2Idx] = tmp;
    }
}

1.1.1 冒泡排序

public class BubbleSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new BubbleSort().bubbleSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    private void bubbleSort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - 1 - i; j++) {
                if (nums[j] > nums[j + 1]) {
                    ArrayUtil.swap(nums, j, j + 1);
                }
            }
        }
    }
}

在这里插入图片描述

1.1.2 快速排序

public class QuickSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new QuickSort().quickSort(nums, 0, nums.length - 1);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    private void quickSort(int[] nums, int start, int end) {
        if (start > end) return;
        int i = start, j = end, base = nums[start];
        while (i < j) {
            while (j >= 0 && nums[j] >= base) j--;
            while (i < j && nums[i] <= base) i++;
            if (i < j) {
                ArrayUtil.swap(nums, i, j);
            }
        }
        ArrayUtil.swap(nums, start, i);
        quickSort(nums, start, i - 1);
        quickSort(nums, i + 1, end);
    }
}

在这里插入图片描述

1.2 插入排序

1.2.1 简单插入排序

public class InsertionSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new InsertionSort().insertionSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    private void insertionSort(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            int j, temp = nums[i];
            for (j = i; j > 0 && nums[j - 1] > temp; j--) {
                nums[j] = nums[j - 1];
            }
            nums[j] = temp;
        }
    }
}

在这里插入图片描述

1.2.2 希尔排序

public class ShellSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new ShellSort().shellSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    private void shellSort(int[] nums) {
        // 缩小增量排序
        for (int gap = nums.length / 2; gap >= 1; gap /= 2) {
            for (int i = gap; i < nums.length; i++) {
                int j, temp = nums[i];
                for (j = i; j >= gap && nums[j - gap] > temp; j-=gap) {
                    nums[j] = nums[j - gap];
                }
                nums[j] = temp;
            }
        }
    }
}

在这里插入图片描述

1.3 选择排序

1.3.1 简单选择排序

public class SelectionSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new SelectionSort().selectionSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    private void selectionSort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] > nums[j]) {
                    ArrayUtil.swap(nums, i, j);
                }
            }
        }
    }
}

在这里插入图片描述

1.3.2 堆排序

public class HeapSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new HeapSort().headSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    private void headSort(int[] nums) {
        int n = nums.length;
        buildHeap(nums, n);
        for (int i = n - 1; i >= 0 ; i--) {
            swap(nums, i, 0);
            heapify(nums, i, 0);
        }
    }

    private void buildHeap(int[] tree, int n) {
        int lastNodeIndex = n - 1;
        int parentNodeIndex = (lastNodeIndex - 1) / 2;
        for (int i = parentNodeIndex; i >= 0; i--) {
            heapify(tree, n, i);
        }
    }

    private void heapify(int[] tree, int n, int i) {
        if (i > n) {
            return;
        }
        int l = 2 * i + 1;
        int r = 2 * i + 2;
        int max = i;
        if (l < n && tree[l] > tree[max]) {
            max = l;
        }
        if (r < n && tree[r] > tree[max]) {
            max = r;
        }
        if (max != i) {
            swap(tree, max, i);
            heapify(tree, n, max);
        }
    }

    private void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

在这里插入图片描述

1.4 归并排序

1.4.1 二路归并排序

public class MergeSort {

    public static void main(String[] args) {
        int[] nums = {6, 8, 10, 9, 4, 5, 2, 7};
        new MergeSort().mergeSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    private void mergeSort(int[] arr, int l, int r) {
        if (l == r) return;
        int m = (l + r) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        merge(arr, l, m + 1, r);
    }

    private void merge(int[] arr, int l, int m, int r) {
        int lSize = m - l;
        int rSize = r - m + 1;
        int[] lArr = new int[lSize];
        int[] rArr = new int[rSize];
        // 1.fill in the left sub array
        if (m - l >= 0) System.arraycopy(arr, l, lArr, 0, lSize);
        // 2.fill in the right sub array
        if (r + 1 - m >= 0) System.arraycopy(arr, m, rArr, 0, rSize);
        // 3.merge into the original array
        int i = 0, j = 0, k = l;
        while (i < lSize && j < rSize) {
            if (lArr[i] < rArr[j]) {
                arr[k++] = lArr[i++];
            } else {
                arr[k++] = rArr[j++];
            }
        }
        while (i < lSize) {
            arr[k++] = lArr[i++];
        }
        while (j < rSize) {
            arr[k++] = rArr[j++];
        }
    }
}

在这里插入图片描述

1.4.2 多路归并排序

待更新...

二、非比较排序

2.1 计数排序

public class CountingSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new CountingSort().countingSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    public void countingSort(int[] nums) {
        int[] mm = getMaxMin(nums);
        int[] cnt = new int[mm[1] - mm[0] + 1];
        for (int num : nums) {
            cnt[num - mm[0]] += 1;
        }
        int idx = 0;
        for (int i = 0; i < cnt.length; i++) {
            for (int j = 0; j < cnt[i]; j++) {
                nums[idx++] = i + mm[0];
            }
        }
    }

    private static int[] getMaxMin(int[] nums) {
        int max = nums[0], min = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > max) max = nums[i];
            if (nums[i] < min) min = nums[i];
        }
        return new int[]{min, max};
    }
}

在这里插入图片描述

2.2 桶排序

public class BucketSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new BucketSort().bucketSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    public void bucketSort(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }

        // 找出数组中的最大值和最小值
        int[] mm = getMaxMin(nums);

        // 初始化桶数组
        int listSize = mm[1] - mm[0] + 1;
        List<List<Integer>> buckets = new ArrayList<>(listSize);
        for (int i = 0; i < listSize; i++) {
            buckets.add(new ArrayList<>());
        }

        // 将数据分配到桶中
        for (int num : nums) {
            buckets.get(num - mm[0]).add(num);
        }

        // 对每个桶进行排序,这里使用了简单的Insertion Sort
        for (List<Integer> numList : buckets) {
            if (!numList.isEmpty()) {
                Collections.sort(numList);
            }
        }

        // 从桶中收集已排序的数据
        int k = 0;
        for (List<Integer> bucket : buckets) {
            for (Integer value : bucket) {
                nums[k++] = value;
            }
        }
    }

    private static int[] getMaxMin(int[] nums) {
        int max = nums[0], min = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > max) max = nums[i];
            if (nums[i] < min) min = nums[i];
        }
        return new int[]{min, max};
    }
}

在这里插入图片描述

2.3 基数排序

public class RadixSort {

    public static void main(String[] args) {
        int[] nums = {12, 34, 11, 98, 56, 49, 21, 29, 19};
        System.out.println("排序前: " + Arrays.toString(nums));
        new RadixSort().radixSort(nums);
        System.out.println("排序后: " + Arrays.toString(nums));
    }

    public void radixSort(int[] nums) {
        int[] mm = getMaxMin(nums);
        int len = String.valueOf(mm[1]).length();
        @SuppressWarnings("unchecked")
        LinkedList<Integer>[] digits = new LinkedList[19];
        for (int powCount = 0; powCount < len; powCount++) {
            for (int num : nums) {
                int idx = (int) Math.abs(num / Math.pow(10, powCount) % 10);
                idx = num >= 0 ? 9 + idx : 9 - idx;
                if (digits[idx] == null) digits[idx] = new LinkedList<>();
                digits[idx].add(num);
            }
            for (int i = 0, j = 0; j < digits.length; j++) {
                while (digits[j] != null && !digits[j].isEmpty()) {
                    nums[i++] = digits[j].removeFirst();
                }
            }
        }
    }

    private static int[] getMaxMin(int[] nums) {
        int max = nums[0], min = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > max) max = nums[i];
            if (nums[i] < min) min = nums[i];
        }
        return new int[]{min, max};
    }
}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1437656.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2024-02-06(Sqoop)

1.Sqoop Apache Sqoop是Hadoop生态体系和RDBMS&#xff08;关系型数据库&#xff09;体系之间传递数据的一种工具。 Sqoop工作机制是将导入或者导出命令翻译成MapReduce程序来实现。在翻译出的MapReduce中主要是对inputformat和outputformat进行定制。 Hadoop生态包括&#…

交易之路:从无知到有知的五个阶段

交易是易学的&#xff0c;它的操作很直观&#xff0c;也是复杂的&#xff0c;它的价格很玄妙。在金融行业日益壮大的背景下&#xff0c;新人辈出&#xff0c;而弱者则逐渐退出。市场生态在不断变化&#xff0c;我们每个人在交易之路上所经历的种种&#xff0c;既清晰可见又模糊…

微信小程序的图片色彩分析,窃取主色调,调色板

1、在微信小程序中创建包管理器 package.json npm init -y 2、安装 Mini App Color Thief 包 npm i --save miniapp-color-thief 3、构建 npm 4、wxml <canvas canvas-id"myCanvas"></canvas> <button bindtap"chooseImage">chooseIm…

阿里云服务器centos_7_9_x64位,3台,搭建k8s集群

目录 1.环境信息 2.搭建过程 2.1 安装Docker源 2.2 安装Docker 2.3 安装kubeadm&#xff0c;kubelet和kubectl 2.4 部署Kubernetes Master(node1) 2.5 安装Pod网络插件&#xff08;CNI&#xff09; 2.6 加入Kubernetes Node 2.7 测试kubernetes集群 3.部署 Dashboard…

百面嵌入式专栏(面试题)内存管理相关面试题1.0

沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本篇我们将介绍内存管理相关面试题 。 一、内存管理相关面试题 page数据结构中的_refcount和_mapcount有什么区别?匿名页面和高速缓存页面有什么区别?page数据结构中有一个锁,我们称为页锁,请问trylock_page()和loc…

uniapp canvas游标卡尺效果

效果 根据公司业务仿照写的效果。原项目从微信小程序转uniapp,未测试该效果在android端效果。 uniapp直接使用canvas不可做子组件,否则无效果显示,其次显示时要考虑页面渲染超时的问题。 如效果所见,可以设置取值精度。 gitee地址:project_practice: 项目练习 - Gitee.…

Docker容器化K8s集群部署教程(一键部署sheel脚本)

本文通过脚本&#xff0c;可以快速地部署和配置Kubernetes环境&#xff0c;省去了各插件手动部署、配置的繁琐过程。 先看最终结果&#xff1a; [rootlocalhost home]# kubectl get node NAME STATUS ROLES AGE VERSION k8smaster Ready control-p…

微软.NET6开发的C#特性——类、结构体和联合体

我是荔园微风&#xff0c;作为一名在IT界整整25年的老兵&#xff0c;看到不少初学者在学习编程语言的过程中如此的痛苦&#xff0c;我决定做点什么&#xff0c;下面我就重点讲讲微软.NET6开发人员需要知道的C#特性。 C#经历了多年发展&#xff0c; 进行了多次重大创新&#xf…

python实现飞书群机器人消息通知(消息卡片)

python实现飞书群机器人消息通知 直接上代码 """ 飞书群机器人发送通知 """ import time import urllib3 import datetimeurllib3.disable_warnings()class FlybookRobotAlert():def __init__(self):self.webhook webhook_urlself.headers {…

机器学习系列——(十五)随机森林回归

引言 在机器学习的众多算法中&#xff0c;随机森林以其出色的准确率、对高维数据的处理能力以及对训练数据集的异常值的鲁棒性而广受欢迎。它是一种集成学习方法&#xff0c;通过构建多个决策树来进行预测和分类。本文将重点介绍随机森林在回归问题中的应用&#xff0c;即随机…

Python进阶--下载想要的格言(基于格言网的Python爬虫程序)

注&#xff1a;由于上篇帖子&#xff08;Python进阶--爬取下载人生格言(基于格言网的Python3爬虫)-CSDN博客&#xff09;篇幅长度的限制&#xff0c;此篇帖子对上篇做一个拓展延伸。 目录 一、爬取格言网中想要内容的url 1、找到想要的内容 2、抓包分析&#xff0c;找到想…

C++之std::tuple(一) : 使用精讲(全)

相关系列文章 C之std::tuple(一) : 使用精讲(全) C三剑客之std::variant(一) : 使用 C三剑客之std::variant(二)&#xff1a;深入剖析 深入理解可变参数(va_list、std::initializer_list和可变参数模版) std::apply源码分析 目录 1.简介 2.std::ignore介绍 3.创建元组 3.1.…

【极数系列】Flink集成KafkaSink 实时输出数据(11)

文章目录 01 引言02 连接器依赖2.1 kafka连接器依赖2.2 base基础依赖 03 使用方法04 序列化器05 指标监控06 项目源码实战6.1 包结构6.2 pom.xml依赖6.3 配置文件6.4 创建sink作业 01 引言 KafkaSink 可将数据流写入一个或多个 Kafka topic 实战源码地址,一键下载可用&#xf…

2024最新CleanMyMac X优化Mac电脑系统体验分享

使用Mac电脑的用户都希望它们能够保持最佳性能。但有时&#xff0c;你可能会发现你的Mac运行变慢或响应迟缓。这可能是由于几个原因造成的&#xff0c;包括硬盘空间不足、系统缓存堆积、以及过多的启动项等。解决了这些问题&#xff0c;你可以显著提升你的Mac性能。本文将探讨导…

寒假作业2024.2.7

1请编程实现二又树的操作 1.1二又树的创建 1.2二又树的先序遍历 1.3二又树的中序遍历 1.4二又树的后序遍历 1.5二又树各个节点度的个数 1.6二叉树的深度 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <…

【JS逆向六】(上)逆向模拟生成某网站的【sig】和【payload】的值 仅供学习

逆向日期&#xff1a;2024.02.07 使用工具&#xff1a;Node.js 加密方法&#xff1a;未知 / md5标准库 文章全程已做去敏处理&#xff01;&#xff01;&#xff01; 【需要做的可联系我】 可使用AES进行解密处理&#xff08; 直接解密即可&#xff09;&#xff1a;在线AES加解…

[HCIE]防火墙基础配置

实验目的&#xff1a;1.允许主机 ping FW的物理接口&#xff1b; 2.允许FW访问trust区域的主机&#xff1b; 3.允许trust主机访问其他所有区域。 配置步骤&#xff1a; 1.配置所有接口地址&#xff08;略&#xff09; 2.将防火墙接口加入到各自的区域 firewall zone trust …

企业数字化转型面临什么挑战?

随着科技的飞速发展&#xff0c;企业数字化转型已成为当今商业世界的一大趋势。然而&#xff0c;在这场变革中&#xff0c;企业可能会面临诸多挑战。本文将结合实际案例&#xff0c;探讨企业在数字化转型过程中可能遇到的一些问题&#xff0c;并提供相应的解决建议。 1.技术挑…

C# CAD交互界面-自定义窗体(三)

运行环境 vs2022 c# cad2016 调试成功 一、引用 二、开发代码进行详细的说明 初始化与获取AutoCAD核心对象&#xff1a; Database db HostApplicationServices.WorkingDatabase;&#xff1a;这行代码获取当前工作中的AutoCAD数据库对象。在AutoCAD中&#xff0c;所有图形数…

研发误删的库,凭什么要 DBA 承担责任

镇楼图 三个角色 删库以及更宽泛的数据库变更场景中有三个角色&#xff0c;业务研发&#xff0c;DBA 以及使用的数据库变更工具&#xff1a; 业务研发通常指的是后端研发。国内最主流的技术栈还是 Java&#xff0c;此外 Go 也有一部分&#xff0c;另有全栈的则使用 Node。这些…