forked from algorithm019/algorithm019
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
36 lines (28 loc) · 858 Bytes
/
InsertionSort.java
File metadata and controls
36 lines (28 loc) · 858 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Arrays;
/**
* Description: 插入排序
* 对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入
* 时间复杂度:O(n^2)
* Date: 2020-12-26
* Time: 11:53 AM
*/
public class InsertionSort {
int[] insertionSort(int[] arr) {
int len = arr.length;
int preIndex = 0;
int cur = 0;
for (int i = 1; i < len; i++) {
preIndex = i-1;
cur = arr[i];
while(preIndex>=0 && arr[preIndex] > cur){
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = cur;
}
return arr;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new InsertionSort().insertionSort(new int[]{1, 4, 3, 7, 2, 10, 5, 21, 6})));
}
}