Binary Search

package Search;
import java.util.Scanner;
public class BinarySearch {
    static final int N=15;
    public static void quick(int[] arr, int start, int end) {        
        
           int low = start;   
           int high = end;    
           int pivot = arr[low];      
           while (low < high) {       
           while (low < high && arr[high] >= pivot) {       
               high--;            
               }   
           arr[low] = arr[high];
           while (low < high && arr[low] <= pivot) {     
               low++;       
               }           
           arr[high] = arr[low]; 
           }
           arr[low] = pivot;   
           if (end <= start)
           {          
              return; 
           }    
      quick(arr, start, low - 1); 
      quick(arr, low + 1, end); 
      }     
    static int binarySearch(int a[],int len,int key)
    {
        int mid,low,high;
        low=0;
        high=len;
        mid=(int)(low+high)/2;
        while(low<=high)
        {
            if(a[mid]==key)
            {
                return mid;
            }
            else if(a[mid]<key)
            {
                low=mid++;
            }
            else
                high=mid--;
        }
        return -1;
    }
    public static void main(String[] args)
    {
        int x,n,i;
        int[] array = new int[N];
        
        for(i=0;i<N;i++)
        {
            array[i]=(int)(100+Math.random()*(100+1));
        }
        System.out.println("the original number is :");
        for(i=0;i<N;i++)
        {
            System.out.println(array[i]);
        }
        
        quick(array,0,N-1);
        System.out.println("the sorted array is :");
        for(i=0;i<N;i++)
            {
                System.out.print(array[i]+"\n");
            }
        
        System.out.println("enter the number to look for");
        Scanner input=new Scanner(System.in);
        x=input.nextInt();
        
        n=binarySearch(array,N,x);
        if (n<0)
        {
            System.out.println("number not found");
        }
        else
        {
            System.out.println("the index of number is :"+(n+1));
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容