C and C++

Moderators: None (Apply to moderate this forum)
Number of threads: 28647
Number of posts: 94663

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Recursive Binary Search Posted by encoded00 on 8 Dec 2010 at 4:33 PM
OK, I had to redo a binary search in which you have to search for 45 in a list of 10 integers. The previous program I was able to get working and it output the correct "Line 5: 45 found at position 3". Not so much with the recursive version. I'm thinking it's something simple/obvious, but I'm not seeing it. Could I please get a little input/advice/help. Thank you to all who graciously posts. Regards.
header.h file

template<class Type>
int binarySearch(const Type list[],Type length, const Type& item){

	int first = 0,
		last = length - 1,
		mid;
	bool found = false;
	
	if (first <= last){ // first check to see it it needs to go any further.
		return -1;
		mid = (first + last) / 2;

		if(list[mid] == item) // if found item, 45.. true if so
			found = true;
		
		else if (list[mid] > item)
			return  binarySearch (list, mid -1, item) ; //passing the list, mid, and item - which is 45. for bottom/lowwer  list
		else
			return binarySearch (list, mid + 1,item);   //passing the list, mid, and item - which is 45. for top/higher list

	/*if(found)
		return mid;  // just left over from binary part. should not be needed, ( i wouldn't think)
	else
		return -1;*/

	}//end if's
}//end binarySearch
______________________________________________________________________
main.cpp file

#include <iostream>
#include "binarySearch.h"
using namespace std;

int main(){
	
	int intList[] = {2, 16, 34, 45, 53, 56, 69, 70, 75, 96}; // list of 10 integers with 45 in "middle"
	int pos;

	pos = binarySearch(intList,10,45);  // length is 10, item is 45
	if(pos != -1)
		cout << "Line 5: " << 45
		<< " found at position "
		<< pos << endl;
	else
		cout << "Line 7: " << 45
		<< " is not in intList " << endl;

	cin.sync();
	cin.peek();
}






 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.