MCPcopy Index your code
hub / github.com/hustcc/JS-Sorting-Algorithm / InsertSort

Class InsertSort

src/java/main/InsertSort.java:6–34  ·  view source on GitHub ↗

插入排序

Source from the content-addressed store, hash-verified

4 * 插入排序
5 */
6public class InsertSort implements IArraySort {
7
8 @Override
9 public int[] sort(int[] sourceArray) throws Exception {
10 // 对 arr 进行拷贝,不改变参数内容
11 int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
12
13 // 从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的
14 for (int i = 1; i < arr.length; i++) {
15
16 // 记录要插入的数据
17 int tmp = arr[i];
18
19 // 从已经排序的序列最右边的开始比较,找到比其小的数
20 int j = i;
21 while (j > 0 && tmp < arr[j - 1]) {
22 arr[j] = arr[j - 1];
23 j--;
24 }
25
26 // 存在比其小的数,插入
27 if (j != i) {
28 arr[j] = tmp;
29 }
30
31 }
32 return arr;
33 }
34}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected