Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javatechie.ds;
- public class BinarySearch {
- public int search(int no, int array[]) {
- int left = 0;
- int right = array.length ;
- while (left<=right) {
- int mid = left + (right - left) / 2;
- if (no == array[mid]) {
- return mid;
- }
- if (no < array[mid]) {
- //search left side
- right = mid - 1;
- }
- if (no > array[mid]) {
- left = mid + 1;
- //search right side
- }
- }
- return -1;
- }
- public static void main(String[] args) {
- int arr[] = { 2, 3, 4, 10, 40 };
- int x = 10;
- int result = new BS().search(x,arr);
- System.out.println(result);
- }
- }
Add Comment
Please, Sign In to add comment