Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I need help for my binary search of Book list based on sorted book array result. I am still new in this field, my Bubble sort is working fine, but I got stuck at Binary Search, my program cannot find the appropriate book ID from the Sorted List for displaying output related to book ID. I really appreciate your advices.

C++
void Swap(TYPE &first, TYPE &last)
{
	TYPE temp;
	temp = first;
	first = last;
	last = temp;
}


C++
void BubbleSort(Book *array[], int size)
{	
	int smallest;
	for(int first = 0; first < size - 1; first++)
	{
		smallest = first;
		for(int current = smallest + 1; current < size; current++)
		{
			if(*array[current] < *array[smallest])
				smallest = current;
		}
		Swap(array[first],array[smallest]);
	}
}


C++
bool BinarySeach(Book *array[], int size, unsigned int bookID, Book *sortedOutput)
{
	int first = 0;
	int last = size - 1;
	int middle;
	int position = -1;
 
	while(first <= last)
	{
		middle = (first + last)/2;
	        
                if(array[middle] == sortedOutput)
	        {
 		  position = middle;
		  return (true);
	        }
		else if(array[middle] > sortedOutput)
		{
		  last = middle - 1;
		}
		else
		{
		  first = middle + 1;
		}
	}
	return (false);
}


main program output
//sortedOutput(bookID,Bookname);
List of sorted Book 
101 - Dummy Adobe Photoshop
102 - HTML,CSS
103 - Visual Studio 2008
 
Please enter ID to search: 102
ID not found, please try again


Thank you for your help
Posted
Updated 24-Sep-11 0:56am
v2

In the line:
C++
if(*array[middle] > sortedOutput)

are you sure you want the indirection operator (*)?
 
Share this answer
 
Comments
Albert Holguin 25-Sep-11 17:19pm    
OP posted as solution:
Thanks for the reply,

That was my mistake, it should not have * in that line.
Your binary search function only returns the fact that it found (or did not find) the item, it does not return where it found it so it's usefullness is reduced to just "Is the item in the list?", not "Where is the item?".
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900