当前位置:网站首页>插入排序总结
插入排序总结
2022-07-16 23:57:00 【十三豆啊】
前言
今天还是接着学十大排序算法,总结的是插入算法
1.定义
插入排序是一种简单直观的排序算法。
2.算法思路
把n个待排序的元素看成为一个有序表和一个无序表。开始时有序表中只包含1个元素,无序表中包含有n-1个元素,排序过程中每次从无序表中取出第一个元素,将它插入到有序表中的适当位置,使之成为新的有序表,重复n-1次可完成排序过程。(其实关键就在于无序表插入有序表)
那么它是具体是怎么操作的呢?上面举个例子
3.例子
假设有一串初始数列{4,7,2,1,3,5}
1.一开始有序表只包含1个元素,就是{4}
2.从第二个位置7来和第一个位置4比较,4比较小,不交换位置得到{4,7}
3.从第三个位置2和前面的位置7比较,比7小,和7交换位置,依次往前比较。得到{2,4,7}
4.从第四个位置1和前面的位置7比较,比7小,和7交换位置,依次往前比较,得到{1,2,4,7}
…n轮过去后
n.得到一个有序数列{1,2,3,4,5,7}
4.代码实现
import java.util.Arrays;
public class insertSort {
public static void main(String[] args) {
int[] arr = {4,7,2,1,3,5};
insertSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void swap(int[] arr,int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void insertSort(int[] arr){
for(int i = 1; i < arr.length; i++){
for (int j = i; j > 0;j--){
if (arr[j] < arr[j-1]){
swap(arr,j,j-1);
}
else {
break;
}
}
}
}
}
5.特点
算法稳定性:稳定
时间复杂度:O(n²)
边栏推荐
- 【无标题】
- C语言基础演练(5)
- Greenplum common
- 25 performance testing articles
- 按住 Day 27 :服务
- 18. Sum of four numbers (15 enhanced version) [ans.add (arrays.aslist (nums[i], nums[j], nums[l], nums[r])]
- Flowable workflow (flowable database table structure)
- Vite3.0 发布
- sqli-labs less-1(报错注入之extractvalue)
- Coordinate solution of rectangular coordinate system rotation (n*90 °) (1 ≤ n ≤ 4)
猜你喜欢

Flowable workflow (flowable database table structure)

【著色器實現Wave效果_Shader效果第一篇】

MySQL - Multi version concurrency control (mvcc)

盛夏防火患!广东开展夏季消防安全检查

交换机与路由器技术:热备份路由选择协议HSRP、HSRP和SPVSTP综合实验

Greenplum6.x客户端连接

抖音抓包通杀版-version21.5

Coordinate solution of rectangular coordinate system rotation (n*90 °) (1 ≤ n ≤ 4)

12. Integer to Roman numerals ●●
![[paper notes] - feature visualization - zfnet - 2014-eccv](/img/e1/4a293b31dae53ece21890140ac3293.png)
[paper notes] - feature visualization - zfnet - 2014-eccv
随机推荐
QT打开外部程序并嵌入Qt界面
Strength certification | Haitai Fangyuan is strongly listed in the top 20 fields of "roar 2022 network security industry map"
LeetCode 242:有效的字母异位词
实力认证|海泰方圆强势上榜《嘶吼2022网络安全产业图谱》20大领域
高等数学---第八章多元函数微分学---多元函数的极值与最值
为什么加工数据指标
Software test interview question collection -- continuous summary and update
从22顶会看对比学习在推荐的应用
【无标题】
war或jar使用Resource或ClassPathResource加载classpath下文件失败
Mysql—锁:全面理解
Hcia-r & s self use notes (8) IP address basis, subnet mask, subnet Division
2. Research on stm32f4 USB protocol - SD card analog USB stick
Baidu page starts from 1 and JPA starts from 0
@ConditionalOnMissingBean 如何实现覆盖第三方组件中的 Bean
Greenplum常用
Uva11362 phone list solution
12 张图,带你彻底理解 ZGC垃圾收集器!
从编译器对指令集的要求看API设计原则
Comment conditionalonmissingbean implémente l'écrasement des haricots dans les composants tiers