数据结构之八大排序算法详解

目录

    • 一、冒泡排序(Bubble Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 二、选择排序(Selection Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 三、插入排序(Insertion Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 四、希尔排序(Shell Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 五、归并排序(Merge Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 六、快速排序(Quick Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 七、堆排序(Heap Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 八、计数排序(Counting Sort)
      • 原理
      • 代码实现
      • 时间复杂度
    • 总结

排序算法是计算机科学中一类重要的算法,用于将数据按照特定的顺序进行排列。以下是对八大排序算法的详细讲解,包括冒泡排序、选择排序、插入排序、希尔排序、归并排序、快速排序、堆排序和计数排序。

一、冒泡排序(Bubble Sort)

原理

冒泡排序是一种简单的排序算法,通过重复地遍历数组,比较相邻的元素并交换顺序,直到整个数组排序完成。

代码实现

public class BubbleSort {public static void bubbleSort(int[] arr) {int n = arr.length;for (int i = 0; i < n - 1; i++) {for (int j = 0; j < n - i - 1; j++) {if (arr[j] > arr[j + 1]) {// 交换 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);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n²)
  • 最优时间复杂度:O(n)(当数组已经排序时)
  • 最差时间复杂度:O(n²)

二、选择排序(Selection Sort)

原理

选择排序通过重复选择最小的元素并将其交换到数组的起始位置,直到整个数组排序完成。

代码实现

public class SelectionSort {public static void selectionSort(int[] arr) {int n = arr.length;for (int i = 0; i < n - 1; i++) {int minIndex = i;for (int j = i + 1; j < n; j++) {if (arr[j] < arr[minIndex]) {minIndex = j;}}// 交换 arr[i] 和 arr[minIndex]int temp = arr[i];arr[i] = arr[minIndex];arr[minIndex] = temp;}}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};selectionSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n²)
  • 最优时间复杂度:O(n²)
  • 最差时间复杂度:O(n²)

三、插入排序(Insertion Sort)

原理

插入排序将数组分为已排序和未排序两个部分,每次从未排序部分取出一个元素,插入到已排序部分的正确位置。

代码实现

public class InsertionSort {public static void insertionSort(int[] arr) {int n = arr.length;for (int i = 1; i < n; ++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 = {64, 34, 25, 12, 22, 11, 90};insertionSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n²)
  • 最优时间复杂度:O(n)(当数组已经排序时)
  • 最差时间复杂度:O(n²)

四、希尔排序(Shell Sort)

原理

希尔排序是一种改进的插入排序,通过将数组分成多个子数组,对每个子数组进行插入排序,然后逐渐缩小子数组的间隔。

代码实现

public class ShellSort {public static void shellSort(int[] arr) {int n = arr.length;for (int gap = n / 2; gap > 0; gap /= 2) {for (int i = gap; i < n; i += 1) {int temp = arr[i];int j;for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {arr[j] = arr[j - gap];}arr[j] = temp;}}}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};shellSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n^(3/2))
  • 最优时间复杂度:O(n)
  • 最差时间复杂度:O(n²)

五、归并排序(Merge Sort)

原理

归并排序是一种分治算法,将数组分为两部分,分别排序,然后将排序后的两部分合并。

代码实现

public class MergeSort {public static void mergeSort(int[] arr) {if (arr == null || arr.length <= 1) {return;}mergeSort(arr, 0, arr.length - 1);}private static void mergeSort(int[] arr, int left, int right) {if (left < right) {int mid = (left + right) / 2;mergeSort(arr, left, mid);mergeSort(arr, mid + 1, right);merge(arr, left, mid, right);}}private static void merge(int[] arr, int left, int mid, int right) {int[] temp = new int[right - left + 1];int i = left, j = mid + 1, k = 0;while (i <= mid && j <= right) {if (arr[i] <= arr[j]) {temp[k++] = arr[i++];} else {temp[k++] = arr[j++];}}while (i <= mid) {temp[k++] = arr[i++];}while (j <= right) {temp[k++] = arr[j++];}System.arraycopy(temp, 0, arr, left, temp.length);}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};mergeSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n log n)
  • 最优时间复杂度:O(n log n)
  • 最差时间复杂度:O(n log n)

六、快速排序(Quick Sort)

原理

快速排序也是一种分治算法,通过选择一个基准元素,将数组分为小于基准和大于基准的两部分,然后递归地对两部分进行排序。

代码实现

public class QuickSort {public static void quickSort(int[] arr) {if (arr == null || arr.length <= 1) {return;}quickSort(arr, 0, arr.length - 1);}private static void quickSort(int[] arr, int left, int right) {if (left >= right) {return;}int pivotIndex = partition(arr, left, right);quickSort(arr, left, pivotIndex - 1);quickSort(arr, pivotIndex + 1, right);}private static int partition(int[] arr, int left, int right) {int pivot = arr[right];int i = left - 1;for (int j = left; j < right; j++) {if (arr[j] <= pivot) {i++;swap(arr, i, j);}}swap(arr, i + 1, right);return i + 1;}private static void swap(int[] arr, int i, int j) {int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};quickSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n log n)
  • 最优时间复杂度:O(n log n)
  • 最差时间复杂度:O(n²)

七、堆排序(Heap Sort)

原理

堆排序是一种基于堆数据结构的排序算法。首先将数组构建成一个最大堆,然后通过交换堆顶元素与数组末尾元素,并重新调整堆,以实现排序。

代码实现

public class HeapSort {public static void heapSort(int[] arr) {int n = arr.length;// 构建最大堆for (int i = n / 2 - 1; i >= 0; i--) {heapify(arr, n, i);}// 提取元素并重新构建堆for (int i = n - 1; i > 0; i--) {swap(arr, 0, i);heapify(arr, i, 0);}}private static void heapify(int[] arr, int n, int i) {int largest = i;int left = 2 * i + 1;int right = 2 * i + 2;if (left < n && arr[left] > arr[largest]) {largest = left;}if (right < n && arr[right] > arr[largest]) {largest = right;}if (largest != i) {swap(arr, i, largest);heapify(arr, n, largest);}}private static void swap(int[] arr, int i, int j) {int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};heapSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n log n)
  • 最优时间复杂度:O(n log n)
  • 最差时间复杂度:O(n log n)

八、计数排序(Counting Sort)

原理

计数排序是一种非比较排序算法,适用于整数排序。通过统计元素出现的次数,然后根据累计的次数将元素放置到正确的位置。

代码实现

public class CountingSort {public static void countingSort(int[] arr) {if (arr == null || arr.length == 0) {return;}int max = arr[0];int min = arr[0];for (int num : arr) {if (num > max) {max = num;}if (num < min) {min = num;}}int range = max - min + 1;int[] count = new int[range];int[] output = new int[arr.length];for (int num : arr) {count[num - min]++;}for (int i = 1; i < range; i++) {count[i] += count[i - 1];}for (int i = arr.length - 1; i >= 0; i--) {output[count[arr[i] - min] - 1] = arr[i];count[arr[i] - min]--;}System.arraycopy(output, 0, arr, 0, arr.length);}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};countingSort(arr);System.out.println("Sorted array: " + Arrays.toString(arr));}
}

时间复杂度

  • 平均时间复杂度:O(n + k)(其中 k 是元素的范围)
  • 最优时间复杂度:O(n + k)
  • 最差时间复杂度:O(n + k)

总结

这八大排序算法各有优缺点,适用于不同的场景。在实际应用中,应根据数据的规模和特点选择合适的排序算法。

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RocketMQ的运行架构

目录 1. 核心组件(1) NameServer(2) Broker(3) Producer(4) Consumer 2. 消息流转流程3. 高可用机制4. 扩展性与负载均衡5.容错机制5. 特殊功能支持6. 典型部署架构总结 RocketMQ 是一款高性能、高可靠的分布式消息中间件&#xff0c;其运行架构设计为分布式、可扩展、高可用的…

【AIGC系列】5:视频生成模型数据处理和预训练流程介绍(Sora、MovieGen、HunyuanVideo)

AIGC系列博文&#xff1a; 【AIGC系列】1&#xff1a;自编码器&#xff08;AutoEncoder, AE&#xff09; 【AIGC系列】2&#xff1a;DALLE 2模型介绍&#xff08;内含扩散模型介绍&#xff09; 【AIGC系列】3&#xff1a;Stable Diffusion模型原理介绍 【AIGC系列】4&#xff1…

算法日记32:15届蓝桥C++B填空(握手问题+小球反弹)

握手问题 一、题解 1、通过观察我们可以发现&#xff0c;题目属于数论中的蜂巢问题&#xff0c;但是我们这里不使用结论&#xff0c;而是通过分析推出 2、假设我们不考虑特殊情况(也就是那 7 7 7个人的情况)&#xff0c;那么问题的答案应该为 int res0; for(int i49;i>1;i…

【三维分割】LangSplat: 3D Language Gaussian Splatting(CVPR 2024 highlight)

论文&#xff1a;https://arxiv.org/pdf/2312.16084 代码&#xff1a;https://github.com/minghanqin/LangSplat 文章目录 一、3D language field二、回顾 Language Fields的挑战三、使用SAM学习层次结构语义四、Language Fields 的 3DGS五、开放词汇查询&#xff08;Open-voca…

Windows安装sql server2017

看了下官网的文档&#xff0c;似乎只有ubuntu18.04可以安装&#xff0c;其他debian系的都不行&#xff0c;还有通过docker的方式安装的。 双击进入下载的ISO&#xff0c;点击执行可执行文件&#xff0c;并选择“是” 不要勾选 警告而已&#xff0c;不必理会 至少勾选这两…

LabVIEW图像识别抗干扰分析

问题描述 在基于LabVIEW的探针定位系统中&#xff0c;存在两个核心技术难点&#xff1a; 相机畸变导致初始定位误差&#xff1a;非线性畸变使探针无法通过坐标变换直接精确定位&#xff0c;需采用粗定位图像修正的两段式控制策略。 图像识别可靠性不足&#xff1a;复杂背景&a…

Leetcode1 两数之和 python两种方法实现

Leetcode1 两数之和 python两种方法实现 文章目录 Leetcode1 两数之和 python两种方法实现方法一&#xff1a;枚举法&#xff08;暴力解法&#xff09;方法二&#xff1a;用空间换时间。 给定一个整数数组 nums 和一个整数目标值 target&#xff0c;请你在该数组中找出 和为…

总结前端常用数据结构 之 队列篇【JavaScript 】

推动你的事业&#xff0c;不要让你的事业推动你。——爱因斯坦 目录 队列是什么&#xff1f;JS异步、事件循环、任务队列&#xff1a;队列的实现方法&#xff1a;‌数组实现‌ - 封装队列&#xff1a;对象实现&#xff08;优化性能&#xff09;- 封装队列&#xff1a; 队列应用…

C# 数据转换

1. 文本框读取byte&#xff0c;ushort格式数据 byte addr; if (byte.TryParse(textBoxAddr.Text, out addr) true) {}2. 字节数组 (byte[]) 转换为 ASCII 字符串 byte[] bytes { 72, 101, 108, 108, 111 }; // "Hello" 的 ASCII 码 string s0 Encoding.ASCII.Ge…

golang部分语法介绍(range关键字,函数定义+特性,结构体初始化+结构体指针/方法)

目录 golang语法 range关键字 介绍 使用 原理 函数 介绍 定义 特性 结构体 介绍 初始化 结构体指针 结构体方法 方法接收者 golang语法 range关键字 介绍 用于遍历数组&#xff08;array&#xff09;、切片&#xff08;slice&#xff09;、映射&#xff08;ma…

Linux与UDP应用1:翻译软件

UDP应用1&#xff1a;翻译软件 本篇介绍 本篇基于UDP编程接口基本使用中封装的服务器和客户端进行改写&#xff0c;基本功能如下&#xff1a; 从配置文件dict.txt读取到所有的单词和意思客户端向服务端发送英文服务端向客户端发送英文对应的中文意思 配置文件内容 下面的内…

【机器学习】逻辑回归(Logistic Regression)

逻辑回归 逻辑回归逻辑回归的流程Sigmoid函数Sigmoid函数的公式及图像 逻辑回归的损失函数与最优化求解逻辑回归使用梯度下降法求解 逻辑回归 逻辑回归与线性回归都是线性模型&#xff0c;其中线性回归使用线性式来预测数值&#xff0c;逻辑回归使用线性式来进行分类任务。 逻…

IDEA - 查看类的继承结构(通过快捷键查看、通过生成类图查看)

一、通过快捷键查看 在项目中定位到目标类&#xff08;例如&#xff0c;Executor.java&#xff09; 按下快捷键 【Ctrl H】 此时会弹出 Type Hierarchy 窗口&#xff0c;展示所有相关的父类、子类、接口 二、通过生成类图查看 在项目中定位到目标类&#xff08;例如&#x…

Leetcode-1776. Car Fleet II [C++][Java]

目录 一、题目描述 二、解题思路 【C】 【Java】 Leetcode-1776. Car Fleet IIhttps://leetcode.com/problems/car-fleet-ii/description/ 一、题目描述 There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an …

《Python实战进阶》No 9:使用 Celery 实现异步任务队列

第9集&#xff1a;使用 Celery 实现异步任务队列 引言 在现代 Web 应用中&#xff0c;许多操作&#xff08;如发送邮件、处理文件上传、执行复杂计算等&#xff09;可能需要耗费较长时间。如果这些操作直接在主线程中执行&#xff0c;会导致用户请求阻塞&#xff0c;降低用户体…

ue5 创建多列StreeView的方法与理解

创建StreeView的多列样式怎么就像是创建单行单列差不多?貌似就是在单行单列中加入了多列widget? 目录结构: 必备条件 StreeView的多列创建需要的必备条件: 数据基类 CustomItemBase #pragma once /* ---------------------------------- | Name | Value …

Spring的下载与配置

1. 下载spring开发包 下载地址&#xff1a;https://repo.spring.io/webapp/#/artifacts/browse/simple/General/libs-release-local/org/springframework/spring 打开之后可以看到有很多版本供选择&#xff0c;因为视频教程用的是4.2.4版本&#xff0c;于是我也选择这个 右键…

Python + requests实现接口自动化框架

&#x1f345; 点击文末小卡片&#xff0c;免费获取软件测试全套资料&#xff0c;资料在手&#xff0c;涨薪更快 为什么要做接口自动化框架 1、业务与配置的分离 2、数据与程序的分离&#xff1b;数据的变更不影响程序 3、有日志功能&#xff0c;实现无人值守 4、自动发送测…

Linux——基本指令

我们今天学习Linux最基础的指令 ls 指令 语法&#xff1a; ls [选项] [⽬录或⽂件] 功能&#xff1a;对于⽬录&#xff0c;该命令列出该⽬录下的所有⼦⽬录与⽂件。对于⽂件&#xff0c;将列出⽂件名以及其他信 息。 命令中的选项&#xff0c;一次可以传递多个 &#xff0c…

【Godot4.3】自定义简易菜单栏节点ETDMenuBar

概述 Godot中的菜单创建是一个复杂的灾难性工作&#xff0c;往往无从下手&#xff0c;我也是不止一次尝试简化菜单的创建。 从自己去年的发明“简易树形数据”用于简化Tree控件获得灵感&#xff0c;于是尝试编写了用于表示菜单数据的EasyMenuData类&#xff0c;以及对应的纯文…