-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSortedArrayList.java
More file actions
53 lines (41 loc) · 1.03 KB
/
SortedArrayList.java
File metadata and controls
53 lines (41 loc) · 1.03 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
47
48
49
50
51
52
53
package com.adhoc;
import java.util.ArrayList;
import java.util.Comparator;
@SuppressWarnings("serial")
public class SortedArrayList<E> extends ArrayList<E> {
protected final Comparator<E> comparator;
public SortedArrayList() {
comparator = null;
}
@Override
public boolean add(final E o) {
int idx = 0;
if (!isEmpty()) {
idx = findInsertionPoint(o);
}
super.add(idx, o);
return true;
}
public int findInsertionPoint(final E o) {
return findInsertionPoint(o, 0, size() - 1);
}
@SuppressWarnings( {"unchecked"})
protected int compare(final E k1, final E k2) {
if (comparator == null) {
return ((Comparable<E>) k1).compareTo(k2);
}
return comparator.compare(k1, k2);
}
protected int findInsertionPoint(final E o, int low, int high) {
while (low <= high) {
int mid = (low + high) >>> 1;
int delta = compare(get(mid), o);
if (delta > 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
}//end class SortedArrayList