-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortPaths.java
56 lines (50 loc) · 1.61 KB
/
SortPaths.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
import java.util.LinkedList;
public class SortPaths implements ISortPaths {
/**
* This sorts with bubbles to sort the path by fastest travel time
*
* @param unsorted The array we are sorting
* @return The sorted array of paths
*/
@Override
public Path[] sort(Path[] unsorted) {
Path[] sorted = new Path[unsorted.length];
System.arraycopy(unsorted, 0, sorted, 0, unsorted.length);
int n = sorted.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (sorted[j].getCost() > sorted[j + 1].getCost()) {
// swap arr[j+1] and arr[j]
Path temp = sorted[j];
sorted[j] = sorted[j + 1];
sorted[j + 1] = temp;
}
}
}
return sorted;
}
@Override
public Path shortestPath(Path[] unsorted) {
LinkedList<Path> paths = new LinkedList<>();
paths.add(unsorted[0]);
for (Path p : unsorted) {
if (paths.get(0).getCost() > p.getCost()) {
paths.add(0, p);
}
}
return paths.get(0);
}
@Override
public Path fewestDoors(Path[] unsorted) {
// In case of same number of doors we take the fastest path
Path sort[] = sort(unsorted);
LinkedList<Path> paths = new LinkedList<>();
paths.add(sort[0]);
for (Path p : sort) {
if (paths.get(0).getPath().size() > p.getPath().size()) {
paths.add(0, p);
}
}
return paths.get(0);
}
}