-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
46 lines (39 loc) · 1.14 KB
/
Copy pathInsertionSort.java
File metadata and controls
46 lines (39 loc) · 1.14 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
/**
* InsertionSort Algorithm is implemented based on
* university lecture materials.
*/
import java.util.ArrayList;
public class InsertionSort implements SortingAlgorithm{
private long start,end;
@Override
public ArrayList<Integer> sort(ArrayList<Integer> input) {
int n = input.size();
start = System.nanoTime();
/**
* For each element in the list:
* start with the second element in the input list
* compare it to the element indexing before current
* move each element to the right
* of current if bigger than current
* */
for (int i =1; i<n; i++){
int curr = input.get(i);
int j = i-1;
while((j > -1) && (input.get(j).compareTo(curr) == 1)) {
input.set(j+1, input.get(j));
j--;
}
input.set(j+1, curr);
}
end=System.nanoTime();
return input;
}
@Override
public long executionTime() {
return end-start;
}
@Override
public String getAlgorithmName() {
return "Insertion Sort";
}
}