/
Sort.java
81 lines (79 loc) · 2.2 KB
/
Sort.java
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
70
71
72
73
74
75
76
77
78
79
80
81
package sorting;
import java.util.*;
public class Sort {
public static int[] insertion_sort (int[] array) {
int n = array.length;
for (int i = 0 ; i < n; i++) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j+1] = array[j];
j = j -1;
}
array[j + 1] = key;
}
return array;
}
/*
* n: the size of the output array
* k: the maximum value in the array
*/
public static int[] generate_random_array (int n, int k) {
List<Integer> list;
int[] array;
Random rnd;
rnd = new Random(System.currentTimeMillis());
list = new ArrayList<Integer> ();
for (int i = 1; i <= n; i++)
list.add(new Integer(rnd.nextInt(k+1)));
Collections.shuffle(list, rnd);
array = new int[n];
for (int i = 0; i < n; i++)
array[i] = list.get(i).intValue();
return array;
}
/*
* n: the size of the output array
*/
public static int[] generate_random_array (int n) {
List<Integer> list;
int[] array;
list = new ArrayList<Integer> ();
for (int i = 1; i <= n; i++)
list.add(new Integer(i));
Collections.shuffle(list, new Random(System.currentTimeMillis()));
array = new int[n];
for (int i = 0; i < n; i++)
array[i] = list.get(i).intValue();
return array;
}
/*
* Input: an integer array
* Output: true if the array is acsendingly sorted, otherwise return false
*/
public static boolean check_sorted (int[] array) {
for (int i = 1; i < array.length; i++) {
if (array[i-1] > array[i])
return false;
}
return true;
}
public static void print_array (int[] array) {
for (int i = 1; i < array.length; i++)
System.out.print(array[i] + ", ");
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Insertion sort starts ------------------");
for (int n = 100000; n <= 1000000; n=n+100000) {
int[] array = Sort.generate_random_array(n);long t1 = System.currentTimeMillis();
array = Sort.insertion_sort(array);
long t2 = System.currentTimeMillis();
long t = t2 - t1;
boolean flag = Sort.check_sorted(array);
System.out.println(n + "," + t + "," + flag);
}
System.out.println("Insertion sort ends ------------------");
}
}