当前位置:网站首页>[21 Days Learning Challenge] Bubble Sort and Insertion Sort
[21 Days Learning Challenge] Bubble Sort and Insertion Sort
2022-08-02 23:32:00 【Xiao Lu wants to brush the force and deduct the question】
冒泡排序
冒泡排序的英文Bubble Sort,是一种最基础的交换排序.之所以叫做冒泡排序,因为每一个元素都可以像小气泡一样,根据自身大小一点一点向数组的一侧移动.
冒泡排序的步骤
比较相邻的元素.如果第一个比第二个大,就交换他们两个.
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对.这步做完后,最后的元素会是最大的数.
针对所有的元素重复以上的步骤,除了最后一个.
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较.
代码
public static void bubbleSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
// 0 ~ N-1
// 0 ~ N-2
// 0 ~ N-3
for (int e = arr.length - 1; e > 0; e--) {
// 0 ~ e
for (int i = 0; i < e; i++) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
}
}
}
// 交换arr的i和j位置上的值
public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
时间复杂度分析
Because of the compare and swap behavior,The worst case is that each element is swapped from beginning to end
例如[9,8,7,6,5,4,3,2,1,0]
因此时间复杂度为O(n2)
插入排序
插入排序是一种最简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入.
在生活中,The simplest example is the sorting of playing cards,
when sorting playing cards,We'll insert the small row to the front
Just know how to sort playing cards,Then you can quickly understand the insertion sort
代码
public static void insertionSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
// 不只1个数
for (int i = 1; i < arr.length; i++) {
// 0 ~ i 做到有序
for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
swap(arr, j, j + 1);
}
}
}
public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
时间复杂度
The worst case is that each small element must be inserted from the end to the first
例如[9,8,7,6,5,4,3,2,1]
因此时间复杂度为O(n2)
边栏推荐
- 新增指令 v-memo
- 信息学奥赛一本通(1258:【例9.2】数字金字塔)
- 【LeetCode】622. 设计循环队列
- 程序员也许都缺一个“二舅”精神
- 【手撕AHB-APB Bridge】~ AMBA总线 之 APB
- 遇上Mysql亿级优化,怎么办
- Translate My Wonderful | July Moli Translation Program Winners Announced
- pytorch的tensor创建和操作记录
- 广东省数字经济发展指引 1.0之建成数据安全保障体系
- 【 LeetCode 】 1374. Generate each character string is an odd number
猜你喜欢
随机推荐
信息学奥赛一本通(1259:【例9.3】求最长不下降序列)
Linphone 被叫方如何解析来电SIP消息中的自定义头消息
使用位运算实现加减乘除(+、-、*、/)及比较器的用法
基于“无依赖绝对定位”实现的圣杯三栏布局
Meta 与苹果的元宇宙碰撞
Geoip2 - golang golang source code analysis
云平台简介
【数据分析】:什么是数据分析?
【SLAM】DM-VIO(ros版)安装和论文解读
Flutter with internationalized adapter automatically generated
解析List接口中的常用的被实现子类重写的方法
ALV report learning summary
姑姑:给小学生出点口算题
Tencent YunMeng every jie: I experienced by cloud native authors efficiency best practices case
特拉维夫大学 | Efficient Long-Text Understanding with Short-Text Models(使用短文本模型进行高效的长文本理解)
LeetCode:622. 设计循环队列【模拟循环队列】
SCANIA SCANIA OTL tag is introduced
J9数字货币论:识别Web3新的稀缺性:开源开发者
信息学奥赛一本通(1260:【例9.4】拦截导弹(Noip1999))
Axure9的元件用法