-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrderedArrayList.java
115 lines (97 loc) · 2.66 KB
/
OrderedArrayList.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
// Team Frogs (Ruby Friedman, Ivina Wang, Samantha Hua)
// APCS pd07
// Lab02
// 2021-12-13
/**********************************************
* class OrderedArrayList
* wrapper class for ArrayList
* maintains invariant that elements are ordered (ascending)
**********************************************/
import java.util.ArrayList;
public class OrderedArrayList {
// instance of class ArrayList, holding objects of type Integer
// (i.e., objects of a class that implements interface Integer)
private ArrayList<Integer> _data;
// default constructor
// initializes instance variables
public OrderedArrayList() {
_data = new ArrayList<Integer>();
}
public String toString() {
return _data.toString();
}
public Integer remove( int i ) {
return _data.remove(i);
}
public int size() {
return _data.size();
}
public Integer get( int i ) {
return _data.get(i);
}
// inserts newVal at the appropriate index
// maintains ascending order of elements
// uses a linear search to find appropriate index
public boolean addLinear(Integer newVal) {
for (int i = 0; i < _data.size(); i++) {
if (newVal.compareTo(_data.get(i)) < 0) {
_data.add(i, newVal);
return true;
}
}
_data.add(newVal);
return true;
}
// inserts newVal at the appropriate index
// maintains ascending order of elements
// uses a binary search to find appropriate index
public boolean addBinary(Integer newVal) {
if (_data.size() == 0) {
_data.add(newVal);
return true;
}
else if (_data.size() == 1) {
if (_data.get(0) > newVal) {
_data.add(0, newVal);
}
else {
_data.add(newVal);
}
return true;
}
else {
int min = 0;
int max = _data.size()-1;
int mid = 0;
while (min <= max){
mid = (min + max)/2;
if (newVal.compareTo(_data.get(mid)) > 0) {
min = mid + 1;
}
else if (newVal.compareTo(_data.get(mid)) < 0) {
max = mid - 1;
}
else {
_data.add(mid, newVal);
return true;
}
}
_data.add(min, newVal);
return true;
}
}
// main method solely for testing purposes
public static void main( String[] args ) {
OrderedArrayList Franz = new OrderedArrayList();
// testing linear search
for( int i = 0; i < 15; i++ ) {
Franz.addLinear( (int)( 50 * Math.random() ) );
}
System.out.println( Franz );
// testing binary search
Franz = new OrderedArrayList();
for( int i = 0; i < 15; i++ )
Franz.addBinary( (int)( 50 * Math.random() ) );
System.out.println( Franz );
}//end main()
}//end class OrderedArrayList