Wednesday 11 June 2014

Binary Search With out Collections in Java

import java.util.Scanner;

public class BinarySearching {

  /**
  * @param args
  */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] b = new int[7];
    int searchValue = 0, index;
    System.out.println("Enter the numbers");
    Scanner input = new Scanner(System.in);
    for (int i = 0; i < b.length; i++) 
    {
       b[i] = input.nextInt();
    }
    System.out.print("Enter a number to search : ");
    searchValue = input.nextInt();
    index = binarySearch(b, searchValue);
    if (index != -1
    {
         System.out.println("Found at index: " + index);
    }
     else
    {
        System.out.println("Not Found");
    }
}

static int binarySearch(int[] search, int find)
 {
     int first, last, mid;
     first = 0;
     last = search.length - 1;
     while (first <= last)
     {
        mid = (first + last) / 2;
        if (search[mid] == find) 
        {
            return mid;
        }
        else if (search[mid] < find) 
        {
           first = mid + 1;
        } 
        else
        {
           last = mid - 1;
        }
   }
   return -1;
}


}

No comments:

Post a Comment