Programming Challenge: Binary Search

Status
Not open for further replies.

fitten

Ars Legatus Legionis
55,635
Subscriptor++
Metasyntactic":2tv496fq said:
fitten":2tv496fq said:
Also, why not return -low instead of ~low? (just attracted my curiosity).
Because it has the wrong semantics. -0 is 0, and we want to return -1 in that case. You could replace it with "-(low + 1)" (though i haven't proved that to myself just yet).

The point of the return value is to not only tell you if the value is there or not, but to also give you an idea of where you'd want to insert it if it was missing. This has been very handy in the work that i've been doing lately (with objects like interval trees).

Fair enough :) I hadn't thought far into it. Makes sense.
 

BobTheFourth

Ars Praefectus
5,477
Subscriptor
Wrote it in Python:

Code:
def bsearch ( a_to_find, a_list, range_min = 0, range_max = -1 ) :
	if range_max < 0 :
		range_max = len(a_list) - 1
	
	range_mid = ((range_max - range_min) / 2) + range_min
	mid_value = a_list[range_mid]
	
	if a_to_find == mid_value :
		return range_mid
		
	if range_min == range_max : 
		return -1
		
	if a_to_find > mid_value :
		range_min = range_mid + 1
	else : # a_to_find < mid_value
		range_max = range_mid - 1
	
	return bsearch ( a_to_find, a_list, range_min, range_max )

On the first run, I found that I had the a_list & a_to_find arguments backwards in the recursive call. So I guess I technically failed, but I'm giving myself a pass because I changed the order of the arguments while writing the test code, so it was correct before I broke it. ;)

It handles all the test cases I threw at it, but like some others, I neglected to check the empty-list condition, which it fails (with an IndexError).
 

TheEternalVortex

Ars Praefectus
3,094
Subscriptor
jbode":3k3rl4ev said:
Goddammit, I botched it; '>' and '>=' don't mean the same thing, and as a result it missed some keys. Grump. TheEternalVortex, your code has the same bug mine did: it should be "while ($high >= $low)". I traced it through on paper before running it, but my brain substituted '>=' for '>'. I always get tripped up by the little shit.

So count mine as a failure.

Are you sure mine has a bug? If $high == $low then the check after the loop should catch it (if I understand you correctly).
 

FogleBird

Ars Tribunus Militum
2,237
On the first run, I found that I had the a_list & a_to_find arguments backwards in the recursive call. So I guess I technically failed, but I'm giving myself a pass because I changed the order of the arguments while writing the test code, so it was correct before I broke it. ;)

It handles all the test cases I threw at it, but like some others, I neglected to check the empty-list condition, which it fails (with an IndexError).
If you fixed a bug, and it also fails on an empty list, how can you give yourself a "pass"? :)
 
Deffexor":2g2lei95 said:
Personally, I'm surprised that no one has submitted a LISP (or Scheme) solution. I seem to recall doing this exercise once in HS in Pascal and then later in College in Scheme. It was much easier in Scheme, as I recall. Unfortunately, I don't remember either language very well now. :(

Judging by the number of mistakes I made when writing this, neither do I.

Code:
(define (binary-search vec key)
  (let ((vector-end (- (vector-length vec) 1)))
    (if (> vector-end 0)
        (let loop ((start 0) (end vector-end))
          (let ((index (+ start (floor (/ (- end start) 2)))))
            (if (<= 0 start index end vector-end)
                (let ((item (vector-ref vec index)))
                  (cond ((< item key)
                         (loop (+ index 1) end))
                        ((> item key)
                         (loop start (- index 1)))
                        (else index)))
                #f)))
        #f)))
Code:
(<= 0 start index end vector-end)
Gratuitous but too tempting to pass up.

Edit: lol @ bug
 
fitten":tus3t3cz said:
Metasyntactic":tus3t3cz said:
fitten":tus3t3cz said:
Also, why not return -low instead of ~low? (just attracted my curiosity).
Because it has the wrong semantics. -0 is 0, and we want to return -1 in that case. You could replace it with "-(low + 1)" (though i haven't proved that to myself just yet).

The point of the return value is to not only tell you if the value is there or not, but to also give you an idea of where you'd want to insert it if it was missing. This has been very handy in the work that i've been doing lately (with objects like interval trees).

Fair enough :) I hadn't thought far into it. Makes sense.
Glad to help.
 

ourob

Ars Scholae Palatinae
725
Subscriptor
Here's mine in C:

Code:
int binsearch(int *a, int start, int end, int search)
{
	int found = -1;
	int mid = start + (end - start) / 2;

	if (search == a[mid] ) {
		found = mid;
	} else if (start < end) {
		if (search < a[mid]) {
			return binsearch(a, start, mid - 1, search);
		} else {
			return binsearch(a, mid + 1, end, search);
		}
	}

	return found;
}

It's correct as far as I can tell, and the only mistake I made before testing it was a compile error for not passing "search" into the recursive binsearch calls *foreheadslap*. But I didn't have to tweak the algorithm after testing.

I'm thinking about doing a "design patterns" version later along these lines. :D
 

BobTheFourth

Ars Praefectus
5,477
Subscriptor
FogleBird":342mwmyg said:
On the first run, I found that I had the a_list & a_to_find arguments backwards in the recursive call. So I guess I technically failed, but I'm giving myself a pass because I changed the order of the arguments while writing the test code, so it was correct before I broke it. ;)

It handles all the test cases I threw at it, but like some others, I neglected to check the empty-list condition, which it fails (with an IndexError).
If you fixed a bug, and it also fails on an empty list, how can you give yourself a "pass"? :)

Tough crowd :p

I also realized I don't range-check the "range_min" and "range_max" arguments.
 
I did something like this for my Data Structures course about a year ago so it was a nice refresher.

Code:
template <class item>
int bSearch(item* list, int start, int end, const item& obj)
{
	int index = (start+end)/2;
	
	if(list[index] == obj)
		return index;
	else if(start == end)
		return -1;
	else if( list[index] > obj)
		return bSearch(list, start, index-1, obj);
	else
		return bSearch(list, index+1, end, obj);
}

Ran it a couple of times and worked fine.
 

ivanolo

Ars Scholae Palatinae
667
HL7":g2agf94v said:
HappyBunny":g2agf94v said:
When I read further and saw that it was 90% had at least 1 bug and they weren't able to do any testing (except walking through it by hand), that's much less interesting.
That's what I thought at first, but as I've thought about it more, I tend to disagree with this view. Being able to go over your code by hand and reason about what it does is an important skill, because it gives you a different view of your code than testing or debugging does. When you step over it by hand, you are the computer, and the advantage is that you can question why you're doing something and whether it's the correct way to do it during every step. You can also think about boundary conditions on every step and whether they might apply. It can be an opportunity to catch bugs you might not catch during testing or even step-through debugging.

For example, at one point when I was writing the algorithm, I included the midpoint again in the next call. This is unnecessary -- we just established that our key was either less than or greater than the midpoint, so the midpoint should be excluded -- and it results in several extra comparisons. It might also produce the wrong result -- I'm not sure because I never got to that point. As I walked through the code by hand, I stopped to ask myself "Why am I doing so many comparisons? This doesn't feel like a binary search" and then I found the error. If it had produced the correct result (and I'm not sure it would have), I might have not found the bug at all and declared it correct.

Then there's this:
Code:
int mid = (low + high) / 2;
It took years for this bug to be flushed out by testing, but it really should have been found in just a few minutes of thinking about the code. The problem is that it was proven correct and published, and once this happens, too few people ever think to question it or check it for bugs. But you're adding two integers together -- the possibility for overflow always exists in that case, and you should always ask whether it's possible for x + y to be greater than the max value for the data type (the same applies for multiplication, and for subtraction or division when one term can be negative). The overflow condition is easier to see while you're writing it -- if you're trained to look for it -- than it is to find during testing. You might catch the bug above during testing if you thought to construct a test case for it, but it would be better to write it in a way that never produces overflow under any condition. And this does require the skill of thinking about your code and getting certain things right before you even test them.

I can't say I felt this way a week ago, but after this thread and another with similar content, I realize how important it is to parse through code and verify its correctness rather than assuming we'll find everything during debugging.
So... pardon my ignorance, but how would you get around using a midpoint?
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
TheEternalVortex":2waoagva said:
jbode":2waoagva said:
Goddammit, I botched it; '>' and '>=' don't mean the same thing, and as a result it missed some keys. Grump. TheEternalVortex, your code has the same bug mine did: it should be "while ($high >= $low)". I traced it through on paper before running it, but my brain substituted '>=' for '>'. I always get tripped up by the little shit.

So count mine as a failure.

Are you sure mine has a bug? If $high == $low then the check after the loop should catch it (if I understand you correctly).

Argh. Yes, your check catches that case (that my code missed). Never mind.
 
Status
Not open for further replies.