|
-
June 21st, 2011, 03:24 AM
#1
binary search algorithm implementation causes stackoverflow error
hi,
I am trying to learn how to write recursive functions.
Here, I tried to create a recursive implementation of binary search algorithm. The algorithm works fine but when the number of elements to search is increased(say 35 elements) a stackoverflowerror exception is raised.
here is the code.
Code:
package algorithms;
public class BinarySearch {
int len;
int[] inputs;
int search_element;
int elementfoundatindex;
public void setInputs(int[] ip)
{
len = ip.length;
inputs = new int[len];
inputs = ip;
}
public void setSearch_element(int se)
{
search_element = se;
}
public int BinarySearchAlgorithm(int prev_index)
{
if(search_element == inputs[inputs.length-1])
return inputs.length-1;
if(search_element == inputs[0])
return 0;
if(prev_index < 0 || prev_index > len)
{
return -1;
}
else
{
if(search_element == inputs[prev_index])
{
return prev_index;
}
else if(search_element > inputs[prev_index])
{
return BinarySearchAlgorithm(prev_index + (int) ((double) prev_index/2.0));
}
else if(search_element < inputs[prev_index])
{
return BinarySearchAlgorithm((int) ((double) prev_index/2.0));
}
else
{
return -9;
}
}
}
}
the class and its member variables get their values from textboxes in a JFrame (which also calls the BinarySearchAlgorithm() on a onclick event for a button).
kindly suggest me ways of making this implementation work for large number of elements.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|