Friday, October 25, 2013

BINARY SEARCH ALGORITHM IN JAVA.

/*
TOPIC: BINARY SEARCH ALGORITHM.
DATE:9/10/2012
*/
import java.util.*;
import java.io.*;
class binsearch
{
int a[];
int size,middle,left,right,key;
PrintStream p=System.out;
Scanner sc=new Scanner(System.in);
binsearch()
{
sc=new Scanner(System.in);

}
void getData()
{


p.println("enter array size");
size=sc.nextInt();
a=new int[size];
p.println("enter array the array");
for(int i=0;i<a.length;i++)

{
p.print("a["+(i)+"] =");
a[i]=sc.nextInt();
}
p.println("the array is");
for(int i=0;i<a.length;i++)
{
p.print(a[i]+" ");
}
p.println();

this.SelectionSort();
this.getKey();

}
void getKey()
{

p.print("enter key: ");
key=sc.nextInt();
this.binsearch();
}
void swap(int i,int j)
{
a[i]=a[i]*a[j];
a[j]=a[i]/a[j];
a[i]=a[i]/a[j];
}
void display()
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
void binsearch()
{
boolean flag=true;
left=0;
right=size-1;
while(left<=right)
{
middle=(left+right)/2;
if(key==a[middle])
{
flag=false;
p.println("the element is found at the "+middle+" position");
break;
}
if(key<a[middle])
{
right=middle - 1;
}
if(key>a[middle])
{
left=middle + 1;
}
}
if(flag)
p.println("element not found");
}
void SelectionSort()
{
for(int i=0;i<a.length-1;i++)
{

for(int j=i+1;j<a.length;j++)
{
if(a[j]<a[i])
swap(j,i);

}
}
System.out.println("AFTER SORTING--we used seletion sort");
display();
}
public static void main(String args[])throws Exception
{
binsearch b=new binsearch();
b.getData();
}
}
/*
OUTPUT:
enter array size
8
enter array the array
a[0] =25
a[1] =1
a[2] =245
a[3] =655
a[4] =22
a[5] =885
a[6] =65
a[7] =36
the array is
25      1       245     655     22      885     65      36
AFTER SORTING--we used seletion sort
1               22              25              36              65             245              655             885
enter key: 655
the element is found at the 6
*/

No comments:

Post a Comment