Analysis of Algorithms (AOA)

Binary Search using Iterative/Simple Method

/*
	Program to Search a Number using Iterative/Simple Binary Search in Java
	Author: PracsPedia		www.pracspedia.com
*/
import java.io.*;
import java.util.*;
class IterativeBinarySearch
{
     public static void main(String[] args)throws IOException
     {
		int i;
		int n = 0;
		int key, t;
		int flag;     
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the no. of elements to be stored :");
		n = sc.nextInt();
		int x[] = new int[n];
		System.out.println("Enter the elements please :");
		for (i = 0 ; i < n ; i++)
       		x[i] = sc.nextInt();
			
		//for-loop for sorting the input
		for(i=0;i < n;i++)
		{
			for(int j= 0;j < n-1-i;j++)
			{
				if(x[j] > x[j+1])
				{
					t = x[j];
					x[j] = x[j+1];
					x[j+1] = t;
				}
			}
		}
		System.out.println("Elements in sorted order:");
		//for loop to display the sorted input
		for(i =0; i < n;i++)
			System.out.print(x[i]+"\t");
       	       	
		System.out.println();	
		System.out.println("Enter the element to be searched :");
		key = sc.nextInt();
		flag = Binary_Search(x,key,0,n);
       	
		if (flag == -1)
			System.out.println("Element not present");
		else
			System.out.println("Element present at location :  " + (flag+1));
	}
	static int Binary_Search(int k[], int key, int low, int high)
	{
		int mid = (low+high)/2;
		while(high >= low)
		{
			if(k[mid] == key)
				return(mid);
			else
			{
				if(key > k[mid])
					low = mid + 1;
				
				else
					high = mid - 1;
				mid = (low + high)/ 2;		
			}
		}
		return (-1);
	}
}
Download Source Code Program List

Sample Ouput

iterative binary search output