-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSort.java
76 lines (64 loc) · 1.86 KB
/
QuickSort.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
/**
* QuickSort Algorithm implementation is based on
* https://www.geeksforgeeks.org/java-program-for-quicksort/
*/
import java.util.ArrayList;
public class QuickSort implements SortingAlgorithm{
private long start,end;
@Override
public ArrayList<Integer> sort(ArrayList<Integer> input) {
start = System.nanoTime();
/**
* check if input array is empty
* */
if(input.isEmpty()){
end = System.nanoTime();
return input;
}
/**
* initialize two ArrayLists to hold the values
* of each partition with
* @param pivot being the last element in the list
* */
ArrayList<Integer> low = new ArrayList<>();
ArrayList<Integer> high = new ArrayList<>();
int pivot = input.get((input.size()-1));
/**
* sort input elements into two partitions depending on
* @param pivot
* */
for (int i = 0; i < input.size(); i++){
if(input.get(i) <= pivot){
if(i == input.indexOf(pivot)){
continue;
}
low.add(input.get(i));
} else {
high.add(input.get(i));
}
}
end = System.nanoTime();
return merge(sort(low), pivot, sort(high));
}
/**
* helper method to merge
* @param low
* @param pivot
* @param high
* */
public ArrayList<Integer> merge(ArrayList<Integer> low, int pivot, ArrayList<Integer> high){
ArrayList<Integer> result = new ArrayList<>();
result.addAll(low);
result.add(pivot);
result.addAll(high);
return result;
}
@Override
public long executionTime() {
return end-start;
}
@Override
public String getAlgorithmName() {
return "Quick Sort";
}
}