Programming Challenge: Binary Search

Status
Not open for further replies.
Fink_Ployd":2icznb7x said:
Wrote one like a month ago, actually..

Code:
/*
 * Returns the smallest key greater than the search key.
 * This is because we index by the end, not the beginning
 */
static int btree_bsearch(struct btree_key *data[], int nkeys, uint64_t search)
{
	int l = 1, r = nkeys + 1;

	while (l < r) {
		int m = (l + r) >> 1;
		if (node(data, m)->key > search)
			r = m;
		else
			l = m + 1;
	}

	return l;
}

Not nearly as annoying as getting locking and garbage collection right on a btree.
I believe your code has an overflow error in it. "l + r" can overflow if the values are sufficiently large enough.
 

mert

Ars Tribunus Militum
2,088
Subscriptor
I know you've all been on the edge waiting for an Ada contribution...

Should handle an array with any index range (e.g. -2147483648 .. -2147483639). Takes value to search for from command line (didn't error-check it).
My first attempt FAILED 'cause I forgot to handle case where first and/or last array index was min or max integer. Exception handler added to catch that case.

Code:
with Ada.Command_Line;
with Ada.Text_Io;

procedure Binary_Search_Test is

    type Array_Type is array (Integer range <>) of Integer;

    procedure Binary_Search (The_Presorted_Array : in Array_Type;
                             The_Value_To_Find   : in Integer;
                             The_Result          : out Integer) is

        Midpoint : Integer := The_Presorted_Array'First +
                                 (The_Presorted_Array'Length / 2);
    begin

        if The_Presorted_Array'Length = 0 then
            The_Result := -1;
        elsif The_Value_To_Find = The_Presorted_Array (Midpoint) then
            The_Result := Midpoint;
        elsif The_Value_To_Find < The_Presorted_Array (Midpoint) then
            Binary_Search (The_Presorted_Array
                              (The_Presorted_Array'First .. Midpoint - 1),
                           The_Value_To_Find, The_Result);
        else
            Binary_Search (The_Presorted_Array
                              (Midpoint + 1 .. The_Presorted_Array'Last),
                           The_Value_To_Find, The_Result);
        end if;

    exception
        -- Handle the case when the array bounds but-up against
        -- the min or max integer value.  (Adding or subtracting
        -- one from the Midpoint would go out-of-bounds.)
        when others =>
            The_Result := -1;

    end Binary_Search;

    Result    : Integer;
    Find_This : Integer;

begin -- Binary_Search_Test

    Find_This := Integer'Value (Ada.Command_Line.Argument (1));
    Ada.Text_Io.Put_Line ("Search for: " & Integer'Image (Find_This));

    Binary_Search (The_Presorted_Array => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                   The_Value_To_Find   => Find_This,
                   The_Result          => Result);

    Ada.Text_Io.Put_Line ("The element index = " & Integer'Image (Result));

end Binary_Search_Test;

EDIT: Hmmm. Guess if the array index range happened to include -1, and the search value was found at that exact index, a client could not tell if the value was found or not. Need to fix that, but too lazy (quick idea: raise user defined exception: Value_Not_Found instead of returning -1 for not found).
 

Fink_Ployd

Ars Tribunus Militum
2,748
Metasyntactic":35hxddrq said:
Fink_Ployd":35hxddrq said:
Wrote one like a month ago, actually..

Code:
/*
 * Returns the smallest key greater than the search key.
 * This is because we index by the end, not the beginning
 */
static int btree_bsearch(struct btree_key *data[], int nkeys, uint64_t search)
{
	int l = 1, r = nkeys + 1;

	while (l < r) {
		int m = (l + r) >> 1;
		if (node(data, m)->key > search)
			r = m;
		else
			l = m + 1;
	}

	return l;
}

Not nearly as annoying as getting locking and garbage collection right on a btree.
I believe your code has an overflow error in it. "l + r" can overflow if the values are sufficiently large enough.

It's not generic code, it's to search in a btree node, for my block device caching thingy (hence the name, the comment might've clued you in too.) If you know what a btree is, I'm sure you know what the constraints on my input are going to be like. Also, aliftedlorax beat you to it.
 

Alamout

Ars Legatus Legionis
27,285
^ My main issue with that code is the use of lower-case-L as a variable name. :p
LordHunter317":3sja0um4 said:
Alamout":3sja0um4 said:
This is kind of a silly exercise, though. It's not important for people to write bug-free code on the first try. We're not using punch-cards anymore--testing code is much faster than trying to debug it before you've run it. The fact that most people can't write a bug-free binary search isn't surprising, because no one learns how to program by trying to write completely bug-free code from scratch with no testing My code had a trivial bug that I found in 5 seconds of testing, and now it works.
aliftedlorax's link shows exactly why this isn't the case. Reasoning about boundary conditions is hard, creating test cases for them is often quite harder. What's more distressing is that regardless of how we choose to deal with such cases, we often don't think of them in the first place. Verification is meaningless if we don't know what we want to do.
I think that's somewhat tangential to the point, though. Those things all still apply with an iterative, prototyping style of programming--you still need to test, and you still only test for the things that you can think of. The only difference in this exercise is that you had to test by running the code in your head.

aliftedlorax's example showed that code can still have bugs even after years of extensive testing in practical applications. This exercise shows that code has bugs as soon as you write it, which is a much simpler and more obvious truth.

I guess it depends what the lesson of the exercise is--is it to show that programmers rarely write correct code on the first try? I don't see the point of that lesson--no one learns to do that, and I don't think it's an efficient way to write code anyway. Is it that programmers make mistakes because they can't reason about why something would fail as they write it? It shows that, I suppose, but I think aliftedlorax's link is a far better lesson there: no one saw that bug for years, because it was so subtle and such a distant corner case. Only when it failed in practice--i.e., only after testing--did it come out.
 

sbarnabas

Wise, Aged Ars Veteran
130
Richard Berg":2lvj8jgp said:
Can't you just do .ToList() on your IEnumerables?
Sure, if you don't mind making your binary search O(N).
Yeah, I guess the real solution is to pass in explicit indexes rather than partition your list until we have that immutable list type you mentioned before.

Richard Berg":2lvj8jgp said:
because you return -1 from the recursive call
I think you're confusing my solution with VinceRA's. (which isn't to say I'm super happy about throwing here; I admit my one crutch while writing this was to search MSDN for the least-boneheaded Exception class that fit the scenario)
No, I'm just stupid; when I copied your code to run my tests on it, I returned -1 instead of throwing an exception to match what my tests expected, then conveniently forgot that the bug was of my own introduction.
 

FogleBird

Ars Tribunus Militum
2,237
Alamout, perhaps you should read this bit from the blog where this originated:

A boxer never has to skip rope in the ring, but it’s an important part of his training regime. A concert pianist never has to play D-flat major, four octaves, hands together, ascending and descending, as part of a performance; but he doesn’t for that reason neglect the exercise. An olympic sprinter never lifts weights during the 100 meters final, but he certainly does as part of his preparation. Why would we think that in programming we don’t need to do exercises that are similarly related to our day-to-day work?
 

Alamout

Ars Legatus Legionis
27,285
Where was this? I don't see it on the page. Is it a different post? Edit: Ah, it's in the next post. He's not addressing my argument here, but says he will in a later entry.
FogleBird":3jeduzr1 said:
Alamout, perhaps you should read this bit from the blog where this originated:

A boxer never has to skip rope in the ring, but it’s an important part of his training regime. A concert pianist never has to play D-flat major, four octaves, hands together, ascending and descending, as part of a performance; but he doesn’t for that reason neglect the exercise. An olympic sprinter never lifts weights during the 100 meters final, but he certainly does as part of his preparation. Why would we think that in programming we don’t need to do exercises that are similarly related to our day-to-day work?
I never said that exercises in general are pointless or silly--I like programming puzzles as much as anyone (hell, I even did this one). I'm questioning the point of this exercise.

The above analogy falls down because, while all of those examples will actually improve the performance of the boxer/pianist/etc, I don't think that this exercise is a useful lesson in anything in particular--there's probably always some utility in writing a bit of code, but the "10% of programmers get this right" part is meaningless. The way I see it, the main part of this exercise is "get it right the first time", and I don't think that's a particularly valuable concept in programming.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
The way I see it, the main part of this exercise is "get it right the first time", and I don't think that's a particularly valuable concept in programming.

Nasa and the other space agencies would disagree with your reasoning.
To do that sort of thing you should in fact be able to reason your way through a program to the level of proving it correct.

Will many people need to for big decisions? likely not. Is there inherent value for some industries to there being people who do get it right first time moer often? yes.

Can you get some of the same benefits through testing, absolutely, and many of the same skills that would apply to the reasoning case apply to the testing one (picking the right tests) along with benefits like white box testing that deliberately targets every possible boundary condition. None the less those people that get it right because they work through *everything* are the ones I would rather have implementing my base class library...
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Alamout":10ljyug9 said:
I think that's somewhat tangential to the point, though. Those things all still apply with an iterative, prototyping style of programming--you still need to test, and you still only test for the things that you can think of. The only difference in this exercise is that you had to test by running the code in your head.
No, it's not tangential at all. You're claiming we don't have to reason about our code (though you call it debugging for some unfathomable reason). My points are that this isn't true, and even if it were true its often easier to reason about such problems than to try to emperically test them.

aliftedlorax's example showed that code can still have bugs even after years of extensive testing in practical applications.
Because testing this particular case was not possible until recently. Had the overflow conditions been reasoned about originally, the bug could have been found.

This exercise shows that code has bugs as soon as you write it, which is a much simpler and more obvious truth.
And you really don't think the fact we often don't even try to reason about the code we're going to write has anything to do with it?

I guess it depends what the lesson of the exercise is--is it to show that programmers rarely write correct code on the first try? I don't see the point of that lesson--no one learns to do that, and I don't think it's an efficient way to write code anyway. Is it that programmers make mistakes because they can't reason about why something would fail as they write it? It shows that, I suppose, but I think aliftedlorax's link is a far better lesson there: no one saw that bug for years, because it was so subtle and such a distant corner case. Only when it failed in practice--i.e., only after testing--did it come out.
No I really don't think its subtle at all, I think we'll believe its subtle because we're not actively trained to consider it. What's worse, we're frequently actively trained the other way.
 
FogleBird":16e9t5u0 said:
Alamout, perhaps you should read this bit from the blog where this originated:

A boxer never has to skip rope in the ring, but it’s an important part of his training regime. A concert pianist never has to play D-flat major, four octaves, hands together, ascending and descending, as part of a performance; but he doesn’t for that reason neglect the exercise. An olympic sprinter never lifts weights during the 100 meters final, but he certainly does as part of his preparation. Why would we think that in programming we don’t need to do exercises that are similarly related to our day-to-day work?
I'm not sure why writing a binary search algorithm several times a week would be useful, though.
 

Alamout

Ars Legatus Legionis
27,285
ShaggyCoUk":1xpbhdsy said:
Nasa and the other space agencies would disagree with your reasoning.
To do that sort of thing you should in fact be able to reason your way through a program to the level of proving it correct.
I figured someone would go this route. I didn't say it was worthless, I said it wasn't particularly valuable. Certainly there are scenarios where it's required--but I don't think this exercise is really going to hone your mind for those situations. And there's a huge difference between "works the first time in production" and "works the first time you write it". You're talking about the former and I'm talking about the latter. NASA still tests their code.

LordHunter317":1xpbhdsy said:
No, it's not tangential at all. You're claiming we don't have to reason about our code (though you call it debugging for some unfathomable reason). My points are that this isn't true, and even if it were true its often easier to reason about such problems than to try to emperically test them.
I'd love to see where I said "we don't have to reason about our code". Of course we do, and I never claimed otherwise. But typically, trying to reason through a problem is only easier than testing it if the test is effectively non-deterministic or otherwise very hard to produce--when concurrency is involved, for instance. In most cases, running a test is easier because all you're doing is evaluating the code on your own--letting the computer do its own reasoning (which is what it will do, after all) is both easier and more accurate.

LordHunter317":1xpbhdsy said:
aliftedlorax's example showed that code can still have bugs even after years of extensive testing in practical applications.
Because testing this particular case was not possible until recently. Had the overflow conditions been reasoned about originally, the bug could have been found.
I suppose that depends how you define recently. The problem has been testable for as long as it's been possible to simulate a sequence--you don't need a literal sequence with 2**31 elements to encounter it, you just need something that acts like one. I wrote one in Python (which has long integers) in fairly short order--although it didn't do much, I could have written one that looked in a large file on disk. No one tested it not because it was untestable, only because the use case didn't come up.

"Subtle" isn't a good word for the bug--but it's not obvious. And it's a problem with implementation, not with the algorithm itself. My Python implementation worked fine with long integers, except that Python's len() function can't handle them. Once I wrote that out of the code, the rest was fine, because there were no overflows.

LordHunter317":1xpbhdsy said:
This exercise shows that code has bugs as soon as you write it, which is a much simpler and more obvious truth.
And you really don't think the fact we often don't even try to reason about the code we're going to write has anything to do with it?
You really think I said that?
 
Here's the version i wrote a while back:

Code:
    public static class ListExtensions
    {
        // Searches a list for a given element using a binary search algorithm.
        // Elements of the array are compared to the search value using provided 
        // comparer on the elemetns of the list and the given search value. 
        // This method assumes that the list is already sorted according to the 
        // comparer function; if this is not the case, the result will be 
        // incorrect.
        //
        // The method returns the index of the given value in the list. If the
        // list does not contain the given value, the method returns a negative
        // integer. The bitwise complement operator (~) can be applied to a
        // negative result to produce the index of the first element (if any) that
        // is larger than the given search value.
        public static int BinarySearch<T1, T2>(this IList<T1> list, T2 value, Func<T2, T1, int> compare)
        {
            Contract.Requires<ArgumentNullException>(list != null);
            Contract.Requires<ArgumentNullException>(compare != null);

            var low = 0;
            var high = list.Count - 1;
            while (low <= high)
            {
                var middle = low + ((high - low) / 2);

                var compValue = compare(value, list[middle]);

                if (compValue == 0)
                {
                    return middle;
                }
                else if (compValue < 0)
                {
                    high = middle - 1;
                }
                else
                {
                    low = middle + 1;
                }
            }

            return ~low;
        }

        public static int BinarySearch<T1>(this IList<T1> list, T1 value, IComparer<T1> comparer)
        {
            return BinarySearch(list, value, comparer.Compare);
        }

        public static int BinarySearch<T1>(this IList<T1> list, T1 value)
        {
            return BinarySearch(list, value, Comparer<T1>.Default);
        }
    }
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
AnObfuscator":247dtlxr said:
I'm much more concerned that there are 3rd/4th year CSE students who, after using Java their entire student career, still don't know what generics are or the difference between interfaces and classes
Let me introduce you to half my graduating class.

That they will get jobs depresses me.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
newwb":2areng1s said:
Blacken00100":2areng1s said:
That they will get jobs depresses me.
Oh they'll get jobs. And while you'll be constantly improving your programming abilities, they'll be improving their handshakes, winks, and nods, and soon you'll be working for them.
Unlikely.

<-- also a business major, has an A+ in schmooze
 

TheEternalVortex

Ars Praefectus
3,094
Subscriptor
PHP. Wrote this in a couple minutes. Haven't looked at the thread yet.
Code:
function bsearch($array, $target) {
    if (count($array) == 0) {
        return false;
    }
    $low = 0;
    $high = count($array) - 1;
    while ($high > $low) {
        $mid = floor(($low + $high) / 2);
        if ($array[$mid] > $target) {
            $high = $mid - 1;
        } else if ($array[$mid] < $target) {
            $low = $mid + 1;
        } else {
            return $mid;
        }
    }
    if ($array[$low] == $target) {
        return $low;
    }
    return false;
}
 

fitten

Ars Legatus Legionis
55,635
Subscriptor++
Metasyntactic":2vmvhig9 said:
Here's the version i wrote a while back:

Code:
    public static class ListExtensions
    {
        // Searches a list for a given element using a binary search algorithm.
        // Elements of the array are compared to the search value using provided 
        // comparer on the elemetns of the list and the given search value. 
        // This method assumes that the list is already sorted according to the 
        // comparer function; if this is not the case, the result will be 
        // incorrect.
        //
        // The method returns the index of the given value in the list. If the
        // list does not contain the given value, the method returns a negative
        // integer. The bitwise complement operator (~) can be applied to a
        // negative result to produce the index of the first element (if any) that
        // is larger than the given search value.
        public static int BinarySearch<T1, T2>(this IList<T1> list, T2 value, Func<T2, T1, int> compare)
        {
            Contract.Requires<ArgumentNullException>(list != null);
            Contract.Requires<ArgumentNullException>(compare != null);

            var low = 0;
            var high = list.Count - 1;
            while (low <= high)
            {
                var middle = low + ((high - low) / 2);

                var compValue = compare(value, list[middle]);

                if (compValue == 0)
                {
                    return middle;
                }
                else if (compValue < 0)
                {
                    high = middle - 1;
                }
                else
                {
                    low = middle + 1;
                }
            }

            return ~low;
        }

        public static int BinarySearch<T1>(this IList<T1> list, T1 value, IComparer<T1> comparer)
        {
            return BinarySearch(list, value, comparer.Compare);
        }

        public static int BinarySearch<T1>(this IList<T1> list, T1 value)
        {
            return BinarySearch(list, value, Comparer<T1>.Default);
        }
    }


3rd line of your comments... "elemetns"

Also, why not return -low instead of ~low? (just attracted my curiosity).
 

MooseAreFun

Ars Legatus Legionis
10,827
Subscriptor
Bhelyer":jduttoyn said:
I thought I would ask the same here at Ars, to see how we stack up. Follow the above rules, and post your results!

I read your post and straight away stopped reading the thread. I wrote some assumptions and test ideas, then started coding. Using Python.

I spotted one major design flaw, followed by one or two bugs by working through it in my head, and after about 70 minutes decided that I was 'finished' and would test it.

My first run got an error in my pre-search-assertion-tests; I don't consider that a failure, but if you're strict it might be. My second run was fine and light testing shows success, but if you can find errors please do. Also, I haven't attempted to prove it formally correct. Nor would I know how.

My result is http://pastebin.com/jWL30yt3
 
Well I would guess something like this:
Code:
template<typename Iterator, typename Distance>
Iterator advance(Iterator it, Distance distance)
{
	std::advance(it, distance); // why this function takes its iterator by reference and returns void I will never understand
	return it;
}

template<typename ForwardIterator, typename T, typename StrictWeakOrdering>
bool binary_search(ForwardIterator start, ForwardIterator end, T needle, StrictWeakOrdering comp)
{
	typename ForwardIterator::distance_type length(std::distance(start, end));
	if(0 == length) { return false; }

	ForwardIterator midpoint(advance(start, length / 2));
	if(comp(needle, *midpoint))
	{
		return binary_search(start, midpoint);
	}
	else if(comp(*midpoint, needle))
	{
		return binary_search(++midpoint, end);
	}
	else
	{
		return true;
	}
}
But IRL if I couldn't use std::binary_search I'd use std::lower_bound an an extra couple of tests.
 
fitten":1hhp48w2 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).
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Alamout":1rn7mgl5 said:
ShaggyCoUk":1rn7mgl5 said:
Nasa and the other space agencies would disagree with your reasoning.
To do that sort of thing you should in fact be able to reason your way through a program to the level of proving it correct.
I figured someone would go this route. I didn't say it was worthless, I said it wasn't particularly valuable.
I dunno, I think binary search over array-style sequences that handles large sequences correctly is awfully valuable.

Certainly there are scenarios where it's required--but I don't think this exercise is really going to hone your mind for those situations.
Well, no exercise is going to hone your mind about these situations if one takes your perspective. I'll just say this: the exercise used in my digital design course to demonstrate why trying to test things as correct and demonstrate the need to reason about the whole problem up front was a simple 4-digit security code on a keypad. Logically, binary search is considerably more complicated than that.

I'd love to see where I said "we don't have to reason about our code". Of course we do, and I never claimed otherwise.
You said I can test it instead, and even should do so because its faster than upfront 'debugging'. The equivocation between upfront reasoning and testing means they are interchangable and I can do one or the other, discarding the one I choose not to do. You've been quite consistently dismissive of doing upfront reasoning of any sort, even in the limited situation where I suggested you should!

But typically, trying to reason through a problem is only easier than testing it if the test is effectively non-deterministic or otherwise very hard to produce--when concurrency is involved, for instance.
And you think creating a 2^30 array was feasible in C, Fortran, Pascal, or another common language circa 1980?

I suppose that depends how you define recently. The problem has been testable for as long as it's been possible to simulate a sequence--you don't need a literal sequence with 2**31 elements to encounter it, you just need something that acts like one.
Doing that in a mainstream 1980 language would have required API changes or compiler hacking. Not attractive, and even when you can, I find it hard to believe its actually easier than reasoning about the code.

No one tested it not because it was untestable, only because the use case didn't come up.
Which is no excuse, especially for something so fundamental as a binary search. It's one of the very few algorithms that nearly every language includes in their standard library. We've known about it for 70 years or so!

"Subtle" isn't a good word for the bug--but it's not obvious.
Addition of fixed-precision integers, including the possibility of overflow, is well-and-widely known. Its something we should consider everytime we see a '+' in code.

You really think I said that?
Huh? It was a conjecture about why our world behaves as it does, nothing more. But yes, since you are advocating testing over reasoning even in situations where it clasically would not be done, I'd like you to respond to it.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
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.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
AnObfuscator":q141x6gq said:
I'd only be shocked or concerned if 9 out of 10 programmers couldn't describe the basic logic, or didn't know what the problem was within 5 minutes of fiddling.

Yeah I have to say when I first say this I thought it meant that 90% couldn't implement a binary search at all. That's somewhat shocking. 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.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
ShuggyCoUk":1zv5rjj4 said:
Nasa and the other space agencies would disagree with your reasoning.
To do that sort of thing you should in fact be able to reason your way through a program to the level of proving it correct.

Those kind of applications require extensive design and testing, and sometimes theorem proving. They don't require anything approaching "write this method in a vacuum without testing, and get it right the first time."
 

HL7

Ars Praefectus
3,523
Subscriptor++
HappyBunny":342ct2dv 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.
 

Macam

Ars Tribunus Militum
2,352
A quick crack at this in C# yielded the correct results on the first try:

Code:
 private static int BinarySearch(List<int> sortedArray, int itemToFind)
        {
            List<int> arrayToSearch = sortedArray;
            bool isEmpty = arrayToSearch.Count.Equals(0);
            int elementCount = arrayToSearch.Count;

            if (isEmpty)
            {
                return -1;
            }

            int middleIndex = arrayToSearch.Count / 2;
            int middleValue = arrayToSearch[middleIndex];

            if (itemToFind.Equals(middleValue))
            {
                return arrayToSearch.IndexOf(middleValue);
            }
     
            int elementRemovalCount = elementCount - middleIndex;

            if (itemToFind < middleValue)
            {
               arrayToSearch.RemoveRange(middleIndex, elementRemovalCount);
            }
            else if (itemToFind > middleValue)
            {
               arrayToSearch.RemoveRange(0, elementRemovalCount);
            }
                
            int returnValue = BinarySearch(arrayToSearch, itemToFind);
            return returnValue;
         }

That said, there's a bit of a mismatch in data structures, as I initially was going to make it generic, but opted to just save a bit of writing and go for the simple case using only int types in order to keep things simple and make sure I could execute the key component of the challenge.
 
Was doing Haskell tonight, so here's some quickly tossed together code. Didn't test it at all, except when done, and it seemed to work then.

Code:
l = [x | x <- [1..200], mod x 2 == 0]

bsearch [l] n = 
  if l == n then
    Just l
  else
    Nothing
bsearch ls n | length ls > 1 = 
  let
    pidx = div (length ls) 2
    (ll,lr) = splitAt pidx ls
    pe = head lr
    lr' = tail lr
  in
   if n == pe then
     Just pe
   else 
     if (n < pe) then
       bsearch ll n
     else
       bsearch lr' n
          
           
t1 = bsearch l 11
 

sbarnabas

Wise, Aged Ars Veteran
130
Macam":16919syq said:
A quick crack at this in C# yielded the correct results on the first try:

Code:
            if (itemToFind < middleValue)
            {
               arrayToSearch.RemoveRange(middleIndex, elementRemovalCount);
            }
            else if (itemToFind > middleValue)
            {
               arrayToSearch.RemoveRange(0, elementRemovalCount);
            }

That said, there's a bit of a mismatch in data structures, as I initially was going to make it generic, but opted to just save a bit of writing and go for the simple case using only int types in order to keep things simple and make sure I could execute the key component of the challenge.

I'm pretty sure RemoveRange is O(n)...which makes binary search kind of pointless.
 
HappyBunny":ci5ez037 said:
ShuggyCoUk":ci5ez037 said:
Nasa and the other space agencies would disagree with your reasoning.
To do that sort of thing you should in fact be able to reason your way through a program to the level of proving it correct.

Those kind of applications require extensive design and testing, and sometimes theorem proving. They don't require anything approaching "write this method in a vacuum without testing, and get it right the first time."

In a course on system testing and verification, we read a research paper describing the development of a automated helicopter landing system for the Royal Navy. It had several teams of mathematicians and programmers. The first team spent a year formally defining & mathematically proving the specification. The first year, they produced 0 lines of code and 600 pages of specs & mathematical proofs. The next team implemented this specification. The third team, which had never seen the specification, examined the code, and produced the mathematical statements describing the actual behavior of the code. This result was compared to the original specification, and the differences were analyzed and corrected.

They even went so far as to specify and analyze the hardware & firmware running their code. Pretty intense stuff.
 
SvendTofte":a2pii72x said:
Was doing Haskell tonight, so here's some quickly tossed together code. Didn't test it at all, except when done, and it seemed to work then.

Code:
bsearch [l] n = 
  if l == n then
    Just l
  else
    Nothing
bsearch ls n | length ls > 1 =
  let
    pidx = div (length ls) 2
[...]

The problem here though is that binary search isn't really compatible with the list data structure (applying length to the list argument alone requires a full O(n) traversal of the list.) Quicker just to search linearly, unless comparisons are really expensive.
 
HalfFlat":10bwook0 said:
The problem here though is that binary search isn't really compatible with the list data structure (applying length to the list argument alone requires a full O(n) traversal of the list.) Quicker just to search linearly, unless comparisons are really expensive.

That goes without saying of course. But meh, couldn't be arsed looking up the IArray thing in Haskell, and I had emacs/haskell going anyway! :)
 
Status
Not open for further replies.