• 幾種查找算法Java實現

    2
    Java 算法 C/C++ 12385 次瀏覽
        /** 
         * 類名:SearchTest.java  
         * 說明: 幾種查找方法 
         */  
        public class SearchTest {  
          
            /** 
             * 函數名稱:binarySearch 
             * 說明:二分查找 時間復雜度O(logN) 
             */  
            //驅動例程  
              public static <AnyType extends Comparable<? super AnyType>> int  binary(AnyType[] a,AnyType x){  
                return binary(a,0,a.length-1,x);  
              }  
            //遞歸  
        /*    public static <AnyType extends Comparable<? super AnyType>> int binary(AnyType[] a,int low,int high,AnyType x){ 
                if(low > high) 
                    return -1; 
                int mid = (low + high)/2; 
                if(a[mid].compareTo(x) > 0 ) 
                    return binary(a,low,mid - 1,x); 
                else if(a[mid].compareTo(x) < 0 ) 
                    return binary(a,mid+1,high,x); 
                else return mid; 
                 
            }*/  
            //非遞歸  
            public static <AnyType extends Comparable<? super AnyType>> int binary(AnyType[] a,int low,int high,AnyType x){  
                  
                while(low <= high){  
                    int mid = (low + high)/2;  
                    if(a[mid].compareTo(x) > 0)  
                        high = mid -1;  
                    else if(a[mid].compareTo(x) < 0)  
                        low = mid + 1;  
                    else  
                        return mid;  
                }  
                return -1;  
            }  
            /** 
             * 函數名稱:main  
                * 說明:測試 
             */  
            public static void main(String[] args) {  
                // TODO 自動生成的方法存根  
                Integer[] a = new Integer[]{1,2,3,4,5,6};  
                int x = 3;  
                System.out.println(binary(a,x));  
            }  
          
        }  

    相似問題

    相關經驗

    相關資訊

    相關文檔

  • sesese色