当前位置:网站首页>[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)
边栏推荐
猜你喜欢
随机推荐
LeetCode:622. 设计循环队列【模拟循环队列】
J9 digital theory: the Internet across chain bridge has what effect?
顺序查找和折半查找,看这篇就够了
postgresql autovaccum自动清理
基于 outline 实现头像剪裁以及预览
Fiddle设置接口数据用指定工具查看;Sublime Text设置json数据格式化转换
arm64麒麟安装paddlehub(国产化)
「每周译Go」这次我们来点不一样的!--《How to Code in Go》系列上线
李沐动手学深度学习V2-bert预训练数据集和代码实现
Redis集群配置
EasyExcel实现动态列解析和存表
美国爱荷华州立大学| Improving Distantly Supervised Relation Extraction by Natural Language Inference(通过自然语言推理改进远程监督关系提取)
Tencent YunMeng every jie: I experienced by cloud native authors efficiency best practices case
The so-called fighting skill again gao also afraid of the chopper - partition, depots, table, and the merits of the distributed
PG 之 SQL执行计划
Geoip2 - golang golang source code analysis
如何使用windbg查看C#某个线程的栈大小 ?
太魔人招新啦|快来加入我们吧!
译出我精彩 | 7月墨力翻译计划获奖名单公布
Flutter with internationalized adapter automatically generated








