Use of Templates in Binary Search

May 4, 2014 at 11:51pm
closed account (Eh5fjE8b)
Hey guys, Once again, I need help from you guys regarding an assignment that I have. The assignment is about using templates in C++ for binary search of specific variables(integers, characters and strings). So far, what I have written below is what I have come up with, but I am getting a seg fault. Can someone please point me in the right direction?

1
2

Last edited on May 6, 2014 at 6:19pm
May 5, 2014 at 12:18am
if the value to be searched is less than mid than high needs to be assigned the value of mid. if value to be searched is more than mid, than low needs to be assigned the value of mid.

Look at your code closely. First and last don't ever change, since those don't change,you don't go further in your search.

int mid=(first+last\2)

mid-1 or mid+1 does nothing when you re-assign it with the same values.

Like this your program will run till it crashes because of an overflow on the stack.
Last edited on May 5, 2014 at 12:24am
May 5, 2014 at 12:28am
closed account (Eh5fjE8b)
you mean something like this?

else if (key<a[mid])
{
search(a, first,mid,key,found, location);
}
else if (key>a[mid])
{
search(a, mid,last,key,found, location);
}javascript:editbox1.editSend()
May 5, 2014 at 12:31am
closed account (Eh5fjE8b)
Yeah. This works, but the string part has some problems, Any ideas?
May 5, 2014 at 12:32am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

{
			int mid =(first+last)/2;
			if(key==a[mid])
			{
				found = true;
				location = mid;
				}
			else if (key<a[mid])
			{
                               last=mid-1;
				search(a, first,last,key,found, location);
				}
			else if (key>a[mid])
			{
                              first=mid+1;
				search(a, first,last,key,found, location);
				}
                         }
		



like this
Last edited on May 5, 2014 at 12:34am
May 5, 2014 at 12:35am
closed account (Eh5fjE8b)
Yes. I got that, but for this part, I keep getting compiler errors
1
2
3
//search (stringarray, first, 10, "nonsense", found, location);
			cout << stringarray[location] << "found in location: "<< location<<endl;
			location= 0;
May 5, 2014 at 12:46am
I ran the code with my adjustments, it works and runs fine. What is the compiler saying?
May 5, 2014 at 12:57am
closed account (Eh5fjE8b)
It says
5C.cpp:32:63: error: no matching function for call to 'search(std::string [10], int&, int, const char [9], bool&, int&)'
May 5, 2014 at 1:26am
1
2
3
4
5
template<class T>
	void search(const T a[], int first , int last, T key, bool found, int& location); 

// search (stringarray, first, 10, "nonsense", found, location);
search (stringarray, first, 10, std::string("nonsense"), found, location);


Or
1
2
3
template< class T, class U >
	void search( const T a[], int first , int last, U key, bool found, int& location ); 
search (stringarray, first, 10, "nonsense", found, location);
Topic archived. No new replies allowed.