Binary Search Program for Java | Study Table
import java.util.Scanner;
public class BinarySearch
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter array Strength: ");
int array[] = new int[scanner.nextInt()];
System.out.println("Enter array Elements: ");
for(int i=0; i<array.length; i++) array[i] = scanner.nextInt();
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array.length-1; j++)
{
int temp = 0;
if(array[j]>array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Enter the Element to be Searched: ");
int srch = scanner.nextInt();
int lLimit=0, uLimit=array.length-1, mid=0, flag=0;
while(lLimit<=uLimit)
{
mid = (lLimit + uLimit)/2;
if(array[mid]<srch) lLimit = mid+1;
else if(array[mid]>srch) uLimit = mid-1;
else
{
flag++;
break;
}
}
System.out.println("The Entered array is: ");
for(int i:array) System.out.print(i+" ");
if(flag>0) System.out.println("\nSearch element found at position "+(mid+1));
else System.out.println("Search Element Not found!");
scanner.close();
}
}
Comments
Post a Comment
What's in your mind?