-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortedListImpl.java
129 lines (112 loc) · 2.37 KB
/
SortedListImpl.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.util.Arrays;
public class SortedListImpl<E extends Comparable<E>> implements SortedList<E> {
private int arraysize = 0;
private int size = 0;
@SuppressWarnings("unchecked")
private E[] arr = (E[]) new Comparable[size];
@Override
public void add(E elem) {
if(arraysize >= arr.length) {
if (size <= 0) {
size++;
} else if(arraysize>=arr.length){
size = arraysize * 2;
}
arr = Arrays.copyOf(arr, size);
}
arr[arraysize] = elem;
arraysize++;
swap(elem, searchPos(elem, true));
}
@Override
public void addSortedArray(E[] arr) {
this.arr = Arrays.copyOf(this.arr, arraysize);
@SuppressWarnings("unchecked")
E[] tmpArr = (E[]) new Comparable[arr.length + this.arr.length];
int i = 0;
int j = 0;
int k = 0;
while (i < arr.length && j < this.arr.length) {
if (arr[i].compareTo(this.arr[j]) < 1) {
tmpArr[k] = arr[i];
i++;
} else {
tmpArr[k] = this.arr[j];
j++;
}
k++;
}
E[] rest;
int restIndex;
if (i >= arr.length) {
rest = this.arr;
restIndex = j;
} else {
rest = arr;
restIndex = i;
}
for (int m = restIndex; m < rest.length; m++) {
tmpArr[k] = rest[m];
k++;
}
arraysize += arr.length;
this.arr = Arrays.copyOf(tmpArr, arraysize);
}
@Override
public E get(int ix) {
if (ix < 0 || ix > arraysize)
return null;
return arr[ix];
}
@Override
public int firstIndex(E elem) {
return searchPos(elem, true);
}
@Override
public int lastIndex(E elem) {
return searchPos(elem, false);
}
@Override
public boolean contains(E elem) {
return elem.compareTo(arr[searchPos(elem, true)]) == 0;
}
@Override
public int countBetween(E lo, E hi) {
return lastIndex(hi) - firstIndex(lo) + 1;
}
@Override
public int size() {
return arraysize;
}
private int searchPos(E elem, boolean lower) {
int lo = 0;
int hi = arraysize - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (lower) {
if (elem.compareTo(arr[mid]) > 0) {
lo = mid + 1;
} else {
hi = mid - 1;
}
} else {
if (elem.compareTo(arr[mid]) < 0) {
hi = mid - 1;
} else {
lo = mid + 1;
}
}
}
return lower?lo:hi;
}
private E[] swap(E elem, int lo) {
E tmpE = arr[lo];
arr[lo] = elem;
for (int i = lo + 1; i <= arraysize - 1; i++) {
arr[arraysize - 1] = arr[i];
arr[i] = tmpE;
tmpE = arr[arraysize - 1];
}
return arr;
}
}