1. 程式人生 > >java版資料結構與演算法—陣列

java版資料結構與演算法—陣列

class ArrayTest {

   private long[] a;
   private int nElems;
   public ArrayTest(int max){
      a = new long[max];
      nElems = 0;
   }

   //查詢指定的項
   public boolean find(long searchKey){
      int i;
      for(i=0; i<nElems; i++){
         if(a[i] == searchKey){
            break;
         }
      }
if(i == nElems){ System.out.println("Can't found:" + searchKey); return false; }else { System.out.println("find it:" + searchKey); return true; } } //插入 public void insert(long value){ a[nElems] = value; nElems ++; } //刪除
public boolean delete(long value){ int i; for(i=0; i<nElems; i++){ if(a[i] == value){ break; } } if(i == nElems){ return false; }else { for(int k=i; k<nElems; k++){ a[k] = a[k+1]; } nElems --
; return true; } } //查詢所有元素 public void findAll(){ for(int i=0; i<nElems; i++){ System.out.print(a[i] + " "); } System.out.println(); } public static void main(String[] args){ ArrayTest a = new ArrayTest(100); a.insert(11); a.insert(18); a.insert(16); a.insert(1); a.insert(88); a.insert(66); a.insert(25); a.insert(0); a.insert(35); a.insert(77); a.findAll(); a.find(88); a.delete(66); a.delete(1); a.findAll(); } }

在這裡插入圖片描述