-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSort.java
More file actions
67 lines (54 loc) · 1.49 KB
/
Copy pathInsertSort.java
File metadata and controls
67 lines (54 loc) · 1.49 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package demo;
/**
* Created by Administrator on 2018/3/26.
* 插入排序;
* 时间复杂度O(n^2)
* i作为外循环主要是为了移动j的位置;
*/
public class InsertSort {
public static void sort(Comparable[] arr){
int n = arr.length;
for (int i = 0; i < n; i++) {
Comparable e = arr[i];
int j = i;
for (; j > 0; j--) {
if (arr[j-1].compareTo(e)>0){
//交换这一步骤十分耗时,可以进行优化;
// swap(arr,j,j-1);
arr[j] = arr[j-1];
}else {
break;
}
}
arr[j] = e;
}
}
public static void sort(int[] arr){
int n = arr.length;
for (int i = 0; i < n; i++) {
int e = arr[i];
for (int j = i; j > 0; j--) {
if (arr[j-1] > arr[e]){
// swap(arr,j,j-1);
arr[j] = arr[j-1];
}else {
break;
}
arr[j] = e;
}
// for (int j = i;j>0&&(arr[j]<arr[j-1]);j--){
// swap(arr,j,j-1);
// }
}
}
public static void swap(int[] arr,int i,int j){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static void swap(Comparable[] arr,int i,int j){
Comparable t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}