插入排序

插入排序

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
package cn.llnn.sort;

import java.util.Arrays;

/**
* 插入排序
*
* @author llnn
* @create 2019-09-26 18:01
**/
public class InsertSort {
public static void main(String[] args) {
int[] a = {51, 46, 20, 18, 65, 97, 82, 30, 77, 50};
System.out.println("待排序:" + Arrays.toString(a));
insertSort(a);
System.out.println("结果:" + Arrays.toString(a));
}

private static void insertSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int temp = a[i];
int j = i;
while (j > 0 && a[j - 1] > temp) {
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}

}

}