/**Binary Search*/
import java.util.*;
public class Binarysearch
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
final int SIZE = 30;
System.out.println("Enter the Number Of elements you want to enter ");
int n = input.nextInt();
System.out.printf("Enter %d elements \n",n);
int i=0,j=0;
int [] arr = new int [SIZE];
for(i=0;i<n;i++)
{
arr[i]=input.nextInt();
}
//sorting
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
//print the sorted array
for(i=0;i<n;i++)
{
System.out.printf(arr[i]+"\t");
}
System.out.println();
//enter the value to be found
System.out.println("Enter the value to be found");
int val = input.nextInt();
//find the element
int low=0,high=n,mid=0;
boolean flag = false;
for(i=0;i<n;i++)
{
mid = (low+high)/2;
if(val==arr[mid])
{
flag=true;
break;
}
else if(val>arr[mid])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
if(flag==true)
{
System.out.println("Element is founda "+(mid+1)+" position");
}
else
{
System.out.println("Element is not found");
}
}
}
import java.util.*;
public class Binarysearch
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
final int SIZE = 30;
System.out.println("Enter the Number Of elements you want to enter ");
int n = input.nextInt();
System.out.printf("Enter %d elements \n",n);
int i=0,j=0;
int [] arr = new int [SIZE];
for(i=0;i<n;i++)
{
arr[i]=input.nextInt();
}
//sorting
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
//print the sorted array
for(i=0;i<n;i++)
{
System.out.printf(arr[i]+"\t");
}
System.out.println();
//enter the value to be found
System.out.println("Enter the value to be found");
int val = input.nextInt();
//find the element
int low=0,high=n,mid=0;
boolean flag = false;
for(i=0;i<n;i++)
{
mid = (low+high)/2;
if(val==arr[mid])
{
flag=true;
break;
}
else if(val>arr[mid])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
if(flag==true)
{
System.out.println("Element is founda "+(mid+1)+" position");
}
else
{
System.out.println("Element is not found");
}
}
}
Comments
Post a Comment