-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSort.java
More file actions
69 lines (58 loc) · 1.93 KB
/
InsertSort.java
File metadata and controls
69 lines (58 loc) · 1.93 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
68
69
package com.xfj.sort.insert;
import com.xfj.sort.interfac.Sort;
import com.xfj.sort.select.SelectionSort;
import com.xfj.sort.util.SortGeneratorHelper;
import com.xfj.sort.util.SwapUtil;
import java.util.Arrays;
/**
* Created by asus on 2017/4/15.
*/
public class InsertSort implements Sort{
@Override
public <T extends Comparable> void sort(T[] arr, int n) {
if(n < 1) return;
/*
for(int i = 1;i < n;i++){
for(int j = i ;j >0;j-- ){
if(arr[j].compareTo(arr[j - 1 ]) < 0){
SwapUtil.swap(arr,j,j - 1);
}else
break;
}
}
*/
for(int i = 1;i< n;i++){
T e = arr[i];
int j;
for(j= i;j > 0 && arr[j-1].compareTo(e) > 0;j--){
arr[j] = arr[j-1];
}
arr[j] = e;
}
}
public static <T extends Comparable> void sortPart(T[] t,int low ,int high){
if(t == null || t.length == 0) return;
for(int i = low; i <= high ; i++){
T e = t[i];
int j;
for (j = i; j > low && t[j-1].compareTo(e) >0 ;j--){
t[j] = t[j-1];
}
t[j] = e;
}
}
public static void main(String[] args) {
Integer[] arrtest = SortGeneratorHelper.generatorIntegerArray(10000, 0, 10000);
Sort sort = new InsertSort();
sort.sort(arrtest,1000);
SortGeneratorHelper.printArray(arrtest);
System.out.println("");
System.out.println(SortGeneratorHelper.isSorted(arrtest,1000));
Integer[] clone = Arrays.copyOf(arrtest, 10000);
SortGeneratorHelper.testSort("selectSort",new SelectionSort(),clone,10000);
SortGeneratorHelper.printArray(clone);
System.out.println("");;
SortGeneratorHelper.testSort("insertSort",new InsertSort(),arrtest,10000);
SortGeneratorHelper.printArray(arrtest);
}
}