Skip to content

Commit a0998db

Browse files
committed
第三次提交 插入排序v1.0.0 for 简单排序 v1.0.0
1 parent a68f3a8 commit a0998db

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.oslee.algorithm.sort;
2+
3+
/**
4+
* @version:
5+
* @description:
6+
* @author: Lee
7+
* @create: 2020-03-10 22:37
8+
*/
9+
public class Insertion {
10+
11+
/*
12+
对数组a中的元素进行排序
13+
*/
14+
public static void sort(Comparable[] a){
15+
for (int i = 1; i < a.length; i++) {
16+
for (int j = i; j > 0 ; j--) {
17+
// 比较索引j处的值和索引j-1处的值, 如果索引j-1处的值比索引j处的值大, 则交换数据
18+
// 如果不大, 那么就找到合适的位置了, 退出
19+
if(greater(a[j - 1], a[j])) {
20+
exch(a, j - 1, j);
21+
} else {
22+
break;
23+
}
24+
}
25+
}
26+
}
27+
28+
/*
29+
判断v是否大于w
30+
*/
31+
private static boolean greater(Comparable v, Comparable w){
32+
return v.compareTo(w) > 0;
33+
}
34+
35+
/*
36+
交换a数组中, 索引i和索引j处的值
37+
*/
38+
private static void exch(Comparable[] a, int i, int j){
39+
Comparable temp;
40+
temp = a[i];
41+
a[i] = a[j];
42+
a[j] = temp;
43+
}
44+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.oslee.algorithm.test;
2+
3+
import com.oslee.algorithm.sort.Insertion;
4+
5+
import java.util.Arrays;
6+
7+
/**
8+
* @version:
9+
* @description:
10+
* @author: Lee
11+
* @create: 2020-03-10 22:45
12+
*/
13+
public class InsertionTest {
14+
public static void main(String[] args) {
15+
Integer[] a = {4, 3, 2, 10, 12, 1, 5, 6};
16+
Insertion.sort(a);
17+
System.out.println(Arrays.toString(a));
18+
}
19+
}

0 commit comments

Comments
 (0)