Friday, August 19, 2011

Binary search program using recursive function in BlueJ


Previously we have seen binary search program. In this post We will see how to search a values using recursive function in binary search. The elements are sorted first using a function then the recursive function is invoked to search any specific value.

Codes of binary search using recursive function
  
import java.io.*;
class Binary
{
void sort(int a[],int n)
{
 int i,j,temp,flag;
for(i=0;i< n;i++)
{
 flag=0;
for(j=0;j< n-i-1;j++)
{
 if(a[j] >a[j+1])
{
 flag=1;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
if(flag==0)
break;
}
}

void bS(int target,int value[],int low,int high)
{
  int mid;
  mid=(low+high)/2;
    if (value[mid]==target)
  {
  System.out.println("\nValue found and the location is:"+mid);
  return;
  }
  else if(high
  {
    System.out.println("\nNot found.");
  return;
 }
  else
  {
     mid=(low+high)/2;
   if(target  > value[mid])
   low=mid+1;
   else if(target
   high=mid-1;
   bS(target,value,low,high);
  }
  }
 public static void main(String args[])throws Exception
{
Binary ob=new Binary();
int array[];
int i,x,low,high;
array = new int[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(x=0;x< 10;x++)
{
  System.out.println("Value:");
array[x]=Integer.parseInt(br.readLine());
}
ob.sort(array,10);
low=0;
high=9;
  System.out.println("\nThe values are:-\n");
for(x=0;x< 10;x++)
{
  System.out.println(array[x]);
}
  System.out.println("\nEnter the value to be searched:-");
i=Integer.parseInt(br.readLine());
ob.bS(i,array,low,high);
}
}

2 comments:

  1. the program is not compiling...

    ReplyDelete
    Replies
    1. I have re-checked the program today. There is no problem.

      Delete

Subscribe via email

Enter your email address:

Delivered by FeedBurner