• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Sid_TheBeginner

Binary Search Help Repost.

22 posts in this topic

[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]I've got the logic right and the algo seems to work fine. Now, that's epic for me [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img] But..[/size][/font][/color]

[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]I want to add 2 more features to this code:[/size][/font][/color]

[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]1) Exit on pressing 'x'. For now I'm using -1 to exit.[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]2) Print a message "Element not found" when an element not present in the array is searched for. Yeah, I'm not able to figure that out :|[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]Well, Here goes my code:[/size][/font][/color]

[font=verdana, arial, helvetica, sans-serif][color=#000000][size=3][CODE][/size][/color][/font]

#include<iostream>
using namespace std;

int BinSearch(int data[], int numElements, int searchKey); // Prototype

int main()
{
int data[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int numElements = 23; // Size of the Array is 23!!!
int searchKey;
int found;

for(int i = 0; i < numElements; i++)
cout << data[i] << ", ";
cout << endl;

for(;;)
{
cout << "Enter search key: (-1 to exit) "; // I want to quit when I press 'x'. Please let me know.
cin >> searchKey;

if(searchKey == -1)
{
cout << "Exiting\n";
break;
}

found = BinSearch(data, numElements,searchKey);

cout << searchKey << " is in position " << found << endl;
}

}

int BinSearch(int data[], int numElements, int searchKey)
{
int position, mid;
int beg = 0;
int end = numElements;

// Algorithm Begins.
for(int i = beg; i <= end;)
{
mid = (beg+end)/2;

if(data[mid] == searchKey)
{
return mid;
}
else if(data[mid] > searchKey)
{
end = mid - 1;
}
else if(data[mid] < searchKey)
{
beg = mid + 1;
}
}

}

[font=verdana, arial, helvetica, sans-serif][color=#000000][size=3][/CODE][/size][/color][/font]
Thanks,
--Sid Edited by Sid_TheBeginner
0

Share this post


Link to post
Share on other sites
Didn't the compiler give you a warning message something about [i][font=verdana, arial, helvetica, sans-serif][color=#000000][size=3]BinSearch[/size][/color][/font][/i] not returning a value? Because it's only returning a value, when it's found the element. Hmm.

What does it return when it finds the element? In what range? Hmm. It returns a zero or positive value.

Hmm. That means negative values aren't used. Hmm.

That means we could use negative values for other purposes, such as indication that the element is not used? Yay! Let's use -1 for indicating that no element is found (that's pretty standard).
We could even use more negative numbers for other error codes, such as the input [i]numElements[/i] was negative... That's another story.

But how can we decide if the element is not found? Wait. We already see that the [i][font=verdana, arial, helvetica, sans-serif][color=#000000][size=3]BinSearch[/size][/color][/font][/i] is only returning a value when it's found something. If it doesn't return, then what happens? Hmmm.
We get to the end of the for loop!

So we know we have to [i]return -1[/i] when nothing is found, and we know that we arrive [i][b]after the for loop[/b][/i] when nothing is found.

Let's put a [i]return -1 [b]after the for loop[/b][/i] then!

Yay! We have signalled that we haven't found the element, and we can act upon it by checking the return value of [i][font=verdana, arial, helvetica, sans-serif][color=#000000][size=3]BinSearch[/size][/color][/font][/i] in Main.
Hmm, that also means we successfully decoupled the logic from the input/output.

In this particular program, we can print stuff differently depending on the return value. If it's -1, we print "nothing found". If it's >= 0, we print the value. Edited by szecs
1

Share this post


Link to post
Share on other sites
Damn! What was that?? Lol. I've reposted it [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]
0

Share this post


Link to post
Share on other sites
@szecs Hey, thanks for your replyl!

Do you mean this:

[CODE]
#include<iostream>
using namespace std;

int BinSearch(int data[], int numElements, int searchKey); // Prototype

int main()
{
int data[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int numElements = 23; // Size of the Array is 23!!!
int searchKey;
int found;

for(int i = 0; i < numElements; i++)
cout << data[i] << ", ";
cout << endl;

for(;;)
{
cout << "Enter search key: (-1 to exit) "; // I want to quit when I press 'x'. Please let me know.
cin >> searchKey;

if(searchKey == -1)
{
cout << "Exiting\n";
break;
}

found = BinSearch(data, numElements,searchKey);

if(found == -1)
cout << searchKey << " not found\n";

cout << searchKey << " is in position " << found << endl;
}

}

int BinSearch(int data[], int numElements, int searchKey)
{
int mid;
int beg = 0;
int end = numElements;
bool not_found = 1;

// Algorithm Begins.
for(int i = beg; i <= end;)
{
mid = (beg+end)/2;

if(data[mid] == searchKey)
return mid;

else if(data[mid] > searchKey)
end = mid - 1;

else if(data[mid] < searchKey)
beg = mid + 1;

else
return -1;
}


}
[/CODE]

This doesn't seem to work. Sorry, I didn't completely understand what you meant...

And Yea, the compiler's telling me this:
warning C4715: 'BinSearch' : not all control paths return a value Edited by Sid_TheBeginner
0

Share this post


Link to post
Share on other sites
No. I didn't mean that. Just think over what I said in my first post.
"End of for loop" may be misworded. I meant "after the for loop".

The complier says not all control paths return a value. Can you figure out what path doesn't return in your code?
With your modifications the code still produces this warning message so that means you didn1t insert the [i]return -1[/i] where I implied.

And think about it: what control path doesn't return value? The path that doesn't find the value. Just debug it on paper. That is the exact point where you have to insert the [i]return -1[/i].


Maybe my English sucks, but I think this should be clear.

And please pay attention to warning messages. Edited by szecs
1

Share this post


Link to post
Share on other sites
Thanks! No more warnings now. I'm returning -1 outside the for loop in the BinSearch function [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
But how do I print a message like "Element not found" using that return value -1 ??

Your English doesn't suck, I'm pure rookie [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]
0

Share this post


Link to post
Share on other sites
Some spoonfeeding:

[code]found = BinSearch(data, numElements,searchKey);

if( found == -1 )
{
cout << Element not found << endl;
}
else // if( found >= 0 ) // for other error codes
{
cout << searchKey << " is in position " << found << endl;
}[/code] Edited by szecs
0

Share this post


Link to post
Share on other sites
[quote name='szecs' timestamp='1340952968' post='4953859']
Some spoonfeeding:

[code]found = BinSearch(data, numElements,searchKey);

if( found == -1 )
{
cout << Element not found << endl;
}
else // if( found >= 0 ) // for other error codes
{
cout << searchKey << " is in position " << found << endl;
}[/code]
[/quote]

Thanks for replying. Did You mean this:

[CODE]

#include<iostream>
using namespace std;

int BinSearch(int data[], int numElements, int searchKey); // Prototype

int main()
{
int data[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int numElements = 23; // Size of the Array is 23!!!
int searchKey;
int found;

for(int i = 0; i < numElements; i++)
cout << data[i] << ", ";
cout << endl;

for(;;)
{
cout << "Enter search key: (-1 to exit) "; // I want to quit when I press 'x'. Please let me know.
cin >> searchKey;

if(searchKey == -1)
{
cout << "Exiting\n";
break;
}

found = BinSearch(data, numElements,searchKey);

if(found == -1)
cout << "Not Found!\n";

else cout << searchKey << " is in position " << found << endl;
}

}

int BinSearch(int data[], int numElements, int searchKey)
{
int mid;
int beg = 0;
int end = numElements;

// Algorithm Begins.
for(int i = beg; i <= end;)
{
mid = (beg+end)/2;

if(data[mid] == searchKey)
return mid;

else if(data[mid] > searchKey)
end = mid - 1;

else if(data[mid] < searchKey)
beg = mid + 1;
}
return -1;
}
[/CODE]

Not working. [img]http://public.gamedev.net//public/style_emoticons/default/sad.png[/img] Edited by Sid_TheBeginner
0

Share this post


Link to post
Share on other sites
[quote name='Sid_TheBeginner' timestamp='1340951361' post='4953848']
@szecs Hey, thanks for your replyl!

Do you mean this:

[CODE]
#include<iostream>
using namespace std;

int BinSearch(int data[], int numElements, int searchKey); // Prototype

int main()
{
int data[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int numElements = 23; // Size of the Array is 23!!!
int searchKey;
int found;

for(int i = 0; i < numElements; i++)
cout << data[i] << ", ";
cout << endl;

for(;;)
{
cout << "Enter search key: (-1 to exit) "; // I want to quit when I press 'x'. Please let me know.
cin >> searchKey;

if(searchKey == -1)
{
cout << "Exiting\n";
break;
}

found = BinSearch(data, numElements,searchKey);

if(found == -1)
cout << searchKey << " not found\n";

else cout << searchKey << " is in position " << found << endl;
}

}

int BinSearch(int data[], int numElements, int searchKey)
{
int mid;
int beg = 0;
int end = numElements;
bool not_found = 1;

// Algorithm Begins.
for(int i = beg; i <= end;)
{
mid = (beg+end)/2;

if(data[mid] == searchKey)
return mid;

else if(data[mid] > searchKey)
end = mid - 1;

else if(data[mid] < searchKey)
beg = mid + 1;
}

return -1;

}
[/CODE]

This doesn't seem to work. Sorry, I didn't completely understand what you meant...

And Yea, the compiler's telling me this:
warning C4715: 'BinSearch' : not all control paths return a value
[/quote] Edited by Sid_TheBeginner
0

Share this post


Link to post
Share on other sites
What doesn't work?
Doesn't print stuff? Doesn't print the right value? Never prints "not found"?

What are we debugging here actually??
0

Share this post


Link to post
Share on other sites
[quote name='Sid_TheBeginner' timestamp='1340955794' post='4953875']
I wan't to print "Not found" if a value which isn't found in the array is entered by the user.
[/quote]
I understand what you want, but in order to debug, we need to know what happens.
What happens instead?

Does it even print "whatever key [i] is in position -1[/i]"?

[i]Does the program work as expected when the key is found?[/i]

I don't know what we are debugging here.
Input? I'm not even sure you can input a single key like that. Doesn't cin input a string?
The algorithm? It should be fine
The output? Does it print anything at all?

Please, don't make us to setup a project and recomplie/debug the thing for you.
0

Share this post


Link to post
Share on other sites
One problem is that your loop:
for(int i = beg; i <= end;)
{
mid = (beg+end)/2;

if(data[mid] == searchKey)
return mid;

else if(data[mid] > searchKey)
end = mid - 1;

else if(data[mid] < searchKey)
beg = mid + 1;
}

doesn't exit if the search target is not in the array. You should probably replace for(int i=beg;i<=end;) with while(beg<end), especially since the i variable is not doing anything.
1

Share this post


Link to post
Share on other sites
I replaced for with while that helped. Thank You. @ szecs you're not the only one who didn't notice it [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] . In another forum also, someone has just now figured it. THank you'll

--Sid
0

Share this post


Link to post
Share on other sites
O wow, I didn't see there's no[i] i++[/i] in the [i]for [/i]loop.
So indeed, you have an infinite loop.


It would have been much easier if you explained what happened in the very first place. I didn't know we have to debug [b]the whole thing[/b].


Please, learn to ask questions and learn to describe the problems in detail. Edited by szecs
0

Share this post


Link to post
Share on other sites
[quote name='szecs' timestamp='1340957881' post='4953883']
O wow, I didn't see there's no[i] i++[/i] in the [i]for [/i]loop.
So indeed, you have an infinite loop.


It would have been much easier if you explained what happened in the very first place. I didn't know we have to debug [b]the whole thing[/b].


Please, learn to ask questions and learn to describe the problems in detail.
[/quote]

Sorry... Actually I didn't know there was a problem there. [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]
0

Share this post


Link to post
Share on other sites
Assuming that array is sorted that way, I believe one solution to the endless loop can be:
...
if(found != NULL)
cout << searchKey << " is in position " << found << endl;
else
cout << "Element not found.\n";
}
....
....
for(int i = beg; i <= end;)
{
mid = (beg+end)/2;

if(data[mid] == searchKey)
{
return mid;
}
else if(data[mid] > searchKey)
{
if(searchKey > data[mid-1]) //if searchKey is greater than the immediate previous element then searchKey not exists in array
return NULL;
end = mid - 1;
}
else if(data[mid] < searchKey)
{
if(searchKey < data[mid+1]) //similar to above comment
return NULL;
beg = mid + 1;
}
}
0

Share this post


Link to post
Share on other sites
[quote name='oobee' timestamp='1340961395' post='4953897']
stuff...
[/quote]

As you are probably aware, indexing in C++ starts with zero. And NULL is zero too, so your code is not working as intended.

Plus your code is a lot more messy (with no gain at all) than the original code with the while, and it only breaks the loop with sorted lists.
0

Share this post


Link to post
Share on other sites
@szecs
you're right about NULL, i could use a number like -999 as a flag. But what do you mean by saying break the loop with sorted lists and the original code with while, i think there isn't while loop in original code. I just tried to avoid endless loop in a simple way. Maybe I'm missing something...
0

Share this post


Link to post
Share on other sites
What RulerOfNothing said. Use the [i]while(beg<end)[/i] instead of the buggy [i]for[/i], but with the same contents like in the first post.
0

Share this post


Link to post
Share on other sites
Your for loop doesn't make any sense in the context of the algorithm. You're not iterating over the array - you're leapfrogging over portions of it. The key observation is that the value of "i" is irrelevant in the loop body. Unless you just want to do something N times, this is a sign that something is amiss.
0

Share this post


Link to post
Share on other sites
Facepalm.
Binary search works only with sorted lists.....
Sorry. I didn't really take a look at the algorithm.
0

Share this post


Link to post
Share on other sites
thanks i benefited
[url="http://www.twitter29.com/"][img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img][/url]
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0