algorithm-base/animation-simulation/数据结构和算法/直接插入排序.md

69 lines
3.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
### **Straight Insertion Sort**
![](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/直接插入排序.2marc4epuzy0.gif)
****
```java
class Solution {
public int[] sortArray(int[] nums) {
//注意 i 的初始值为 1也就是第二个元素开始
for (int i = 1; i < nums.length; ++i) {
//待排序的值
int temp = nums[i];
//需要注意
int j;
for (j = i-1; j >= 0; --j) {
//找到合适位置
if (temp < nums[j]) {
nums[j+1] = nums[j];
continue;
}
//跳出循环
break;
}
//插入到合适位置,这也就是我们没有在 for 循环内定义变量的原因
nums[j+1] = temp;
}
return nums;
}
}
```
****
O(n)
2+3+....+n = (n+2)*(n-1)/2,3 +4+5+....n+1 = (n+4)*(n-1)/2,O(n^2).
O(n) n O(n^2)
****
O(1)
****
temp
![](https://cdn.jsdelivr.net/gh/tan45du/bedphoto2@master/20210122/微信截图_20210128084750.6911k6mnrac0.png)