標籤:
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 else35 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 HighArray53 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 else76 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 HighArrayApp88 89 90
運行結果:
77 99 44 55 22 88 11 0 66 33 can‘t Find 35can‘t delete 2342977 44 22 88 11 66 33
【資料結構】數組操作(HighArrayApp.java)