-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchCourses.java
90 lines (75 loc) · 2.28 KB
/
BinarySearchCourses.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
82
83
84
85
86
87
88
89
90
import java.util.Comparator;
import java.util.Arrays;
public class BinarySearchCourses
{
// Returns the index of the first key in a[] that equals the search key, or -1 if no such key.
public static <Key> int firstIndexOfDept(CollegeCourse[] a, String dept, Comparator<CollegeCourse> comparator)
{
Arrays.sort(a, comparator);
int low = 0;
int high = a.length - 1;
int mid = (low + high) / 2;
int lowest = -1;
String midDept;
int comparison;
if (a[low].getDepartment().compareTo(dept) == 0)
{
return low;
}
while (high >= low)
{
midDept = a[mid].getDepartment();
comparison = midDept.compareTo(dept);
if (comparison > 0)
{
high = mid - 1;
}
else if (comparison < 0)
{
low = mid + 1;
}
else
{
lowest = mid;
high = mid - 1;
}
mid = ((high + low) / 2);
}
return lowest;
}
// Returns the index of the last key in a[] that equals the search key, or -1 if no such key.
public static <Key> int lastIndexOfDept(CollegeCourse[] a, String dept, Comparator<CollegeCourse> comparator)
{
Arrays.sort(a, comparator);
int low = 0;
int high = a.length - 1;
int mid = (low + high) / 2;
int highest = -1;
String midDept;
int comparison;
while (high >= low)
{
midDept = a[mid].getDepartment();
comparison = midDept.compareTo(dept);
if (comparison > 0)
{
high = mid - 1;
}
else if (comparison < 0)
{
low = mid + 1;
}
else
{
highest = mid;
low = mid + 1;
}
mid = (int)((high + low) / 2);
}
return highest;
}
// unit testing (required)
public static void main(String[] args)
{
}
}