-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSort.java
More file actions
45 lines (39 loc) · 931 Bytes
/
Copy pathInsertSort.java
File metadata and controls
45 lines (39 loc) · 931 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
37
38
39
40
41
42
43
44
45
package com.albert.algorithm.sort;
import java.util.Arrays;
/**
* 插入排序法
*
* @author Albert
* @see http://baike.baidu.com/view/1443814.htm
*/
public class InsertSort {
public static void main(String[] args) {
int[] array = {6, 5, 3, 9, 0, 2, 7, 6, 4, 12, 11};
sort(array);
}
/**
* 升序
*
* @param array
*/
public static void sort(int[] array) {
printArray(array);
int tmp, index;
for (int i = 0; i < array.length - 1; i++) {
tmp = array[i + 1];
for (index = i; index >= 0; index--) {
if(array[index] > tmp) {
array[index + 1] = array[index];
} else {
break;
}
}
array[index + 1] = tmp;
printArray(array);
}
}
private static void printArray(int[] array) {
System.out.print(Arrays.toString(array));
System.out.println();
}
}