The binary search program can be used it's only a sorted list of elements that means the binary search is used only with the list of elements that already arrange in order
The binary search cannot be used for a list of elements in a random order this process starts comparing the search element if the middle element in the list both are Matched then the result is element found
otherwise we need to check whether the search element is smaller or larger than the middle element in the list if the search element smaller then repeat the same process for the left sublist of the middle element if the search element is larger then we repeat the same process for the rights of sublist of the middle element
repeat this process until we find the set element in the list or until left
with sub list of only element and if that element also doesn't match with the
search element then the result it as element not found in the list
Let us taken an example
A[5]
= [79]. [26]. [88]. [11].
[65]
A[0] a[1]
a[2] a[3] a[4]
By using bubble sort technique the sorted array
A[5]
= [11]. [26]. [65]. [79].
[88]
A[0] a[1]
a[2] a[3] a[4]
Let 79 search element
Start=0,end=4
Mid=0+4/2=2
IF a[mid]=search element then the result is
element found but here a(2)=63=/79(search element)
Now we have to check whether the search element
is less than or greater than a[mid]
65<79
A[mid] search element
Now it will repeat the process on the right sub
array
Start=mid+1 end=4
=2+1
=3
Mid=start+end/2=3+4/2=7/2=3.5=a(3)=79
Here the search element is equal to the a[mid] of
right sub array hence the result will be element
class binarysearch
{
public static void main(String[] args)
{
int i,j,start,end,mid,n,item,temp,flag=0;
Scanner bs = new Scanner(System.in);
System.out.println("Enter Size Of Array :");
n=bs.nextInt();
int[] a;//declaration of array
a=new int[n]; // Creation of array with given size
System.out.println("Enter unsorted Array :");
for(i=0;i<n;i++)
{
System.out.printf("\n Element a[%d] :",i);
a[i]=bs.nextInt();
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.print("\n Sorted Array elements :");
for(i=0;i<n;i++)
{
System.out.print( a[i] +" ");
}
for(i=0;i<n;i++)
{
System.out.printf("\n ADDRESS=%h ---- ARRAY=a[%d]----- DATA=%d --- location=%d\n",i*4,i,a[i],i+1);
}
System.out.print("\n Enter the element to be searched :");
item=bs.nextInt();
start=0;end=n-1;
while(start <= end)
{
mid=(start+end)/2;
if(item < a[mid])
end=mid - 1;
else if(item > a[mid])
start=mid + 1;
else if(item == a[mid])
{
System.out.printf("\n Element %d is found at location %d",item,mid+1);
flag=1;
break;
}
}
if (flag==0)
System.out.printf("\n Element %d is not in the array",item);
}
}
output:
No comments:
Post a Comment