-
Notifications
You must be signed in to change notification settings - Fork 590
/
Copy pathOrderedArray.java
84 lines (67 loc) · 1.9 KB
/
OrderedArray.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
package orderedarray;
public class OrderedArray {
private long[] a; // declaring an array
private int n; //number of data items in the array
public OrderedArray (int max) {
this.a = new long[max];
this.n = 0;
}
public int size() { // return max size of the array
return this.a.length;
}
public int find(long key) {
for (int i = 0; i < n; i++) {
if (a[i] == key) {
return i;
}
}
return -1;
}
public void insert(long value) { // inserting elements into the arrray
if (this.n == size()) {
System.out.println("array is filled , can not insert");
return;
}
for (int i = 0; i < n; i++) {
if (value < a[i]) {
for (int j = n - 1; j >= i; j--) {
this.a[j + 1] = a[j];
}
this.a[i] = value;
this.n++;
return;
}
}
this.a[n] = value;
n++;
}
public boolean delete(long value) {
int index = find(value);
if (index == -1) {
System.out.println("Deletion terminated because could not find the value");
return false;
} else {
for (int i = index; i < n - 1; i++) {
this.a[i] = this.a[i + 1];
}
this.n--;
return true;
}
}
void display() {
for (int i = 0; i < this.n; i++) {
System.out.print(this.a[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
OrderedArray arr = new OrderedArray(7);
arr.insert(7);
arr.insert(8);
arr.insert(3);
arr.insert(4);
arr.display();
arr.delete(11);
arr.display();
}
}