【数据结构】数组操作(HighArrayApp.java)

 1 // java 数据结构和算法第二版 拉佛 著
 2 // 数组的操作
 3 
 4 package first;
 5 
 6 class HighArray {
 7     private long[] a;
 8     private int nElems;
 9     
10     public HighArray(int max) {
11         a = new long[max];
12         nElems = 0;
13     }
14     
15     public void insert(long value) {
16         a[nElems] = value;
17         nElems++;
18     }
19     
20     public void display() {
21         for (int j = 0; j < nElems; j++) {
22             System.out.print(a[j] + " ");
23         }
24         System.out.println(" ");
25     }
26     
27     public boolean find(long searchKey) {
28         int j;
29         for (j = 0; j < nElems; j++) 
30             if (a[j] == searchKey) break;
31                 
32         if (j == nElems)
33             return false;
34         else
35             return true;
36     }
37     
38     public boolean delete(long value) {
39         int j;
40         for (j = 0; j < nElems; j++)
41             if ( a[j] == value ) break;
42         
43         if (j == nElems)
44             return false;
45         else {
46             for (int k = j; k < nElems; k++)
47                 a[k] = a[k + 1];
48             nElems--;
49             return true;
50         }
51     }
52 }// end of class HighArray
53 
54 
55 public class HighArrayApp {
56     public static void main(String[] args) {
57         int maxSize = 100;
58         HighArray arr  = new HighArray(maxSize);
59         
60         arr.insert(77);
61         arr.insert(99);
62         arr.insert(44);
63         arr.insert(55);
64         arr.insert(22);
65         arr.insert(88);
66         arr.insert(11);
67         arr.insert(00);
68         arr.insert(66);
69         arr.insert(33);
70         arr.display();
71         
72         int searchKey = 35;
73         if (arr.find(searchKey))
74             System.out.println("Found" + searchKey);
75         else
76             System.out.println("can't Find " + searchKey);
77         
78         arr.delete(00);
79         arr.delete(55);
80         arr.delete(99);
81         
82         if (arr.delete(23429) == false)
83             System.out.println("can't delete " + 23429);
84         
85         arr.display();
86     }
87 }// end of class HighArrayApp
88 
89 
90 

运行结果:
77 99 44 55 22 88 11 0 66 33  
can't Find 35
can't delete 23429
77 44 22 88 11 66 33  

 

 

 

posted @ 2015-01-11 13:07  Thermo  阅读(331)  评论(0编辑  收藏  举报