Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 93fee52

Browse files
committed
实现插入排序
1 parent 6a2b26f commit 93fee52

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,40 @@
11
package com.mistray.insertion;
22

3+
import com.mistray.model.SortModel;
4+
35
/**
46
* @author MistLight
57
* @create 2018年11月16日
68
* @desc 插入排序
9+
* 时间复杂度:
10+
* 平均情况:O(n^2)
11+
* 最好情况:O(n)
12+
* 最坏情况:O(n^2)
13+
* 空间复杂度:O(1)
14+
* 稳定性:稳定
715
*/
816
public class Insertion {
17+
18+
public static void main(String[] args) {
19+
Integer[] ins = {4, 3, 2, 5, 7, 22, 59, 72, 35, 34};
20+
Insertion.insertionSort(ins);
21+
}
22+
23+
public static void insertionSort(Integer[] ins) {
24+
int n = ins.length;
25+
int i, j;
26+
for (i = 1; i < n; i++) {
27+
// temp为本次循环待插入有序列表中的数
28+
int temp = ins[i];
29+
// 寻找temp插入有序列表的正确位置
30+
for (j = i - 1; j >= 0 && ins[j] > temp; j--) {
31+
//元素后移,为插入temp做准备
32+
ins[j + 1] = ins[j];
33+
}
34+
// 插入temp
35+
ins[j + 1] = temp;
36+
SortModel.show(ins);
37+
}
38+
39+
}
940
}

‎sort/src/main/java/com/mistray/model/SortModel.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public static boolean less(Comparable v, Comparable w) {
1313
return v.compareTo(w) < 0;
1414
}
1515

16-
private static void exch(Comparable[] a, int i, int j) {
16+
public static void exch(Comparable[] a, int i, int j) {
1717
Comparable t = a[i];
1818
a[i] = a[j];
1919
a[j] = t;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /