javatechie

Binary Search

Sep 21st, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. package com.javatechie.ds;
  2.  
  3. public class BinarySearch {
  4.  
  5.     public int search(int no, int array[]) {
  6.        
  7.         int left = 0;
  8.         int right = array.length ;
  9.        
  10.         while (left<=right) {
  11.            
  12.             int mid = left + (right - left) / 2;
  13.            
  14.             if (no == array[mid]) {
  15.                 return mid;
  16.             }
  17.             if (no < array[mid]) {
  18.                 //search left side
  19.                 right = mid - 1;
  20.             }
  21.             if (no > array[mid]) {
  22.                 left = mid + 1;
  23.                 //search right side
  24.             }
  25.         }
  26.         return -1;
  27.     }
  28.  
  29.     public static void main(String[] args) {
  30.         int arr[] = { 2, 3, 4, 10, 40 };
  31.  
  32.         int x = 10;
  33.         int result = new BS().search(x,arr);
  34.         System.out.println(result);
  35.     }
  36. }
Add Comment
Please, Sign In to add comment