-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.java
54 lines (44 loc) · 1.56 KB
/
InsertionSort.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
/*
Date: 10th May,2017
@Author: Naren Vaishnavi
Insertion Sort with time complexity of O(n2).
*/
package insertionsort;
import java.util.Arrays;
import java.util.Random;
public class InsertionSort {
private static final Random random = new Random();
private static final int RANDOM_INT_RANGE = 10;
public static void main(String args[]) {
long time1 = System.currentTimeMillis();
System.out.print("Time Taken:" + time1);
int[] arrsize = assignValues(10000); // call to assignValues method
System.out.println("Before Sorting: " + Arrays.toString(arrsize));
int[] arr2 = doInsertionSort(arrsize);
System.out.println("After Sorting: " + Arrays.toString(arr2));
// time taken to run the algorithm
long time = System.currentTimeMillis();
System.out.print("Time Taken:" + time);
}
private static int[] assignValues(int size) {
final int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(RANDOM_INT_RANGE);
}
return array;
}
// insertion algorithm implementation
public static int[] doInsertionSort(int[] array) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j - 1;
while ((i > -1) && (array[i] > key)) {
array[i + 1] = array[i];
i--;
}
array[i + 1] = key;
}
return array;
}
}