Tue Sep 28 2021

Binary Search

File Name: binary-search.java

import java.io.*;
import java.util.Scanner;

class search {

	/* Constructor of the class */
	search(int list[ ], int srchdata) {

		/* 'min' use for starting location of the array, 'max' use for end location of the array and 'mid' use for middle location of the array */
		int min = 0, max = list.length - 1;
		int mid = (min + max) / 2;
		while(min <= max) {
			if(list[mid] < srchdata)
				min = mid + 1;
			else if(list[mid] == srchdata) {
				System.out.println(srchdata+" is found at location "+(mid+1));
				break;
			}
			else
				max = max - 1;
			mid = (max + min) / 2;
		}
		if(min > max)
			System.out.println(srchdata+" not found on the list!");
	}
}
										
class binarysearch {
	public static void main(String args[ ]) {

		/* For binary search, the array should be arranged in ascending or descending order */
		int list[ ] = {1,2,3,4,5,6,7,8,9,10};
		Scanner input = new Scanner(System.in);
		System.out.println("Enter an number to search:");
		new search(list, Integer.parseInt(input.nextLine()));
	}
}




/* Output */
Enter an number to search:
22

22 not found on the list!

/* -------------------------------- */

Enter an number to search:
2

2 is found at location 2
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.