Javaデータ構造とアルゴリズム(順序配列と二分ルックアップ)を詳細に理解する。


一、概要
秩序配列にはしばしば二分割検索が用いられ、検索の速度を高めることができる。今日、私達は順番で検索して、二分検索して、配列の添削を実現します。
二、秩序配列の長所と短所
利点:検索速度は無秩序配列よりずっと速いです。
短所:挿入する時は順序に従って後のデータを移動します。
三、秩序配列と無秩序配列の共通の長所と短所
データを削除する時は、後のデータを前に移動して削除項目の穴を埋める必要があります。
四、コード実現

public class OrderArray {
  
   private int nElemes; //      
   
   private long[] a;
   
   /**
   *                   
   *
   * @param max
   */
   public OrderArray(int max){
     this.a = new long[max];
     nElemes = 0;
   }
   
   //     (    )
   public int find(long searchElement){
     int startIndex = 0;
     int endIndex = nElemes-1;
     int curIn;
     while(true){
       curIn = (startIndex + endIndex)/2;
       if(a[curIn]==searchElement){
         return curIn; //  
       }else if(startIndex>endIndex){ //]   
         return nElemes; //          
       }else{ //     
         if(a[curIn]<searchElement){
           startIndex = curIn + 1; //      
         }else{ //   
           endIndex = curIn -1;
         }
       }
       
     }
   }
   
   
   //    (    )
   public void insert(long value){
     int j;
     for(j=0;j<nElemes;j++){
       if(a[j]>value){
         break;
       }
     }
     for(int k=nElemes;k>j;k--){
       a[k] = a[k-1];
     }
     a[j] = value;
     nElemes++;
   }
   
   //     
   public boolean delete(long value){
     int j = find(value);
     if(j==nElemes){
       return false; //   
     }else{
       //          
       for(int k=j;k<nElemes;k++)
       a[k] = a[k+1];
       
       nElemes--;
       return true;
     }
   }
   //     
   public void display(){
     for(int i=0;i<nElemes;i++){
       System.out.print(a[i]+" ");
     }
   }
   
   public int size(){
     return nElemes;
   }
}
五、テスト

 public static void main(String[] args) {
     int max = 100;
     OrderArray oa = new OrderArray(max);
     oa.insert(12);
     oa.insert(14);
     oa.insert(90);
     oa.insert(89);
     oa.insert(87);
     oa.insert(88);
     oa.insert(67);
     oa.display();
     int searchkey = 90;
     if(oa.find(searchkey)!=oa.size()){
       System.out.println("found"+searchkey);
     }else{
       System.out.println("not found");
     }
     oa.delete(88);
     oa.delete(90);
     oa.delete(89);
     oa.display();
   }
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。