Binary Search in Array

前端 未结 5 526
生来不讨喜
生来不讨喜 2020-11-27 05:40

How would I implement a binary search using just an array?

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 06:26

    Did implement below code in Java,simple and fast /** * Binary Search using Recursion * @author asharda * */ public class BinSearch {

      /**
       * Simplistic BInary Search using Recursion
       * @param arr
       * @param low
       * @param high
       * @param num
       * @return int
       */
      public int binSearch(int []arr,int low,int high,int num)
      {
        int mid=low+high/2;
        if(num >arr[high] || num arr[mid])
          {
            return binSearch(arr,low+1,high, num);
          }
    
        }//end of while
    
        return -1;
      }
    
      public static void main(String args[])
      {
        int arr[]= {2,4,6,8,10};
        BinSearch s=new BinSearch();
        int n=s.binSearch(arr, 0, arr.length-1, 10);
        String result= n>1?"Number found at "+n:"Number not found";
        System.out.println(result);
      }
    }
    

提交回复
热议问题