forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlowArray.java
More file actions
71 lines (64 loc) · 2.58 KB
/
lowArray.java
File metadata and controls
71 lines (64 loc) · 2.58 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Book: Data Structures and Algorithms in Java, by Robert LaFore
* Chapter 2:
* lowArray.java
* demonstrates array class with low-level interface
* to compile this code: javac lowArray.java
* to run this program: java LowArrayApp
*/
class LowArray {
private long[] a; // ref to array a
//--------------------------------------------------------------
public LowArray(int size) { // constructor
a = new long[size]; // create array
}
//--------------------------------------------------------------
public void setElem(int index, long value) { // set value
a[index] = value;
}
//--------------------------------------------------------------
public long getElem(int index) { // get value
return a[index];
}
//--------------------------------------------------------------
} // end class LowArray
class LowArrayApp {
public static void main(String[] args) {
LowArray arr; // reference
arr = new LowArray(100); // create LowArray object
int nElems = 0; // number of items in array
int j; // loop variable
arr.setElem(0, 77); // insert 10 items
arr.setElem(1, 99);
arr.setElem(2, 44);
arr.setElem(3, 55);
arr.setElem(4, 22);
arr.setElem(5, 88);
arr.setElem(6, 11);
arr.setElem(7, 00);
arr.setElem(8, 66);
arr.setElem(9, 33);
nElems = 10; // now 10 items in array
for (j=0; j<nElems; j++) // display items
System.out.print(arr.getElem(j) + " ");
System.out.println("");
int searchKey = 26; // search for data item
for (j=0; j<nElems; j++) // for each element,
if (arr.getElem(j) == searchKey) // found item?
break;
if (j == nElems) // no
System.out.println("Can't find " + searchKey);
else // yes
System.out.println("Found " + searchKey);
// delete value 55
for (j=0; j<nElems; j++) // look for it
if (arr.getElem(j) == 55)
break;
for (int k=j; k<nElems; k++) // higher ones down
arr.setElem(k, arr.getElem(k+1));
nElems--; // decrement size
for (j=0; j<nElems; j++) // display items
System.out.print(arr.getElem(j) + " ");
System.out.println("");
} // end main()
} // end class LowArrayApp