Programming Challenge: Binary Search

Status
Not open for further replies.

Bhelyer

Well-known member
2,231
http://reprog.wordpress.com/2010/04/19/are-you-one-of-the-10-percent/

I found this quite interesting. Basically, given the following description:

Binary search solves the problem [of searching within a pre-sorted array] by keeping track of a range within the array in which T [i.e. the sought value] must be if it is anywhere in the array. Initially, the range is the entire array. The range is shrunk by comparing its middle element to T and discarding half the range. The process continues until T is discovered in the array, or until the range in which it must lie is known to be empty. In an N-element table, the search uses roughly log(2) N comparisons.

Only about ten percent of the professional programmers given the task of translating the above code into a language of the choice did so correctly, given all the time they needed.

The linked blog post gave the following rules:

Here are the rules:

Use whatever programming language you like.

No cutting, pasting or otherwise copying code. Don’t even look at other binary search code until you’re done.
I need hardly say, no calling bsearch(), or otherwise cheating :)

Take as long as you like — you might finish, and feel confident in your code, after five minutes; or you’re welcome to take eight hours if you want (if you have the time to spare).

You’re allowed to use your compiler to shake out mechanical bugs such as syntax errors or failure to initialise variables, but …

NO TESTING until after you’ve decided your program is correct.

Finally, the most important one: if you decide to begin this exercise, then you must report — either to say that you succeeded, failed or abandoned the attempt. Otherwise the figures will be skewed towards success.

I thought I would ask the same here at Ars, to see how we stack up. Follow the above rules, and post your results!
 

Bhelyer

Well-known member
2,231
And here's the attempt I made for the blog post:

Code:
/**
 * An implementation of the binary search algorithm for
 * http://reprog.wordpress.com/2010/04/19/are-you-one-of-the-10-percent/
 */
module bsearch;


/**
 * Performs a binary search over list 'l' for element 'e'.
 * Returns the index, or -1 on failure.
 *
 * 'base' is for internal use by the function.
 *
 * The return value should be size_t, but we are allowed to ignore overflow.
 */
int bsearch(T)(T[] l, T e, int base = 0)
{
    int index(int i)
    {
        return base + i;
    }

    if (l.length == 0) return -1;
    if (l.length == 1) {
        if (l[0] == e) {
            return index(0);
        } else {
            return -1;
        }
    }

    size_t mid = l.length / 2;
    if (e == l[mid]) {
        return index(mid);
    } else if (e < l[mid]) {
        return bsearch(l[0 .. mid], e, 0 + base);
    } else if (e > l[mid]) {
        return bsearch(l[mid .. $], e, mid + base);
    }

    // We shouldn't reach here.
    assert(false);
}


void main()
{
}


unittest
{
    int[] l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    assert(bsearch(l, 5)  == 4);
    assert(bsearch(l, 1)  == 0);
    assert(bsearch(l, 10) == 9);
    assert(bsearch(l, 11) == -1);
    assert(bsearch(l, 0)  == -1);
    
    int[] ll = [5];
    assert(bsearch(ll, 5) == 0);
    assert(bsearch(ll, 6) == -1);
    assert(bsearch(ll, 4) == -1);
    ll ~= 6;
    assert(bsearch(ll, 5) == 0);
    assert(bsearch(ll, 6) == 1);
    assert(bsearch(ll, 7) == -1);
    assert(bsearch(ll, 4) == -1);

    int[] z = [];
    assert(bsearch(z, 1) == -1);
}

(The language is D 2.0)

It was written following the rules in the OP. It passes all my tests, but I can see one bug:

Code:
return bsearch(l[mid .. $], e, mid + base);

should read

Code:
return bsearch(l[mid+1 .. $], e, mid+1 + base);

And I'm sure you smart folks can find many, many more. D:
 

Mark Cianciosa

Wise, Aged Ars Veteran
161
BinarySearch.jpg


Failed the first time because I didn't realize that LabView's "In Range" function doesn't consider a number in range if that number equals the Max or Min. :mad: So I had to rewrite it to test the trivial case that the number I am searching equals the high, low or half index first.
 

Fink_Ployd

Ars Tribunus Militum
2,748
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.
 

sbarnabas

Wise, Aged Ars Veteran
130
I didn't bother to test this, but it seems correct (doesn't it always?)... C#, recursive (because I figure the CLR can do TCO better than I can):
Code:
 public static int search<T>(T[] array, int start, int end, T item) where T : IComparable
        {
            if (start > end)
            {
                return -1;
            }
            else
            {
                int mid = end - ((end - start) / 2);
                int cmp = array[mid].CompareTo(item);
                if (cmp == 0)
                {
                    return mid;
                }
                if (cmp > 0)
                {
                    return search(array, start, mid - 1, item);
                }
                if (cmp < 0)
                {
                    return search(array, mid + 1, end, item);
                }
                return -1;
            }
        }
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Hard to believe it's been almost a month since I've written any .NET code. Fades quicker than I thought! Here's to some much-needed C# practice:

Code:
int BSearch<T>(IList<T> list, T val) 
    where T : IComparable<T>
{
    if (list.Count == 0)
        throw new KeyNotFoundException();
    
    int midpoint = list.Count >> 1;
    int comparison = val.CompareTo(list[midpoint]);
    if (comparison < 0)
        return BSearch(list.Take(midpoint), val);
    else if (comparison > 0)
        return BSearch(list.Skip(midpoint + 1), val) + midpoint + 1;
    else
        return midpoint;
}

No more VS here; written in Notepad++. Uncompiled, untested, YMMV, etc. I've stared at it awhile but wouldn't be surprised if I land in the 90% failbucket.
 

stickboy

Ars Tribunus Angusticlavius
6,218
Subscriptor
sbarnabas":1su32nmr said:
I didn't bother to test this, but it seems correct (doesn't it always?)... C#, recursive (because I figure the CLR can do TCO better than I can):
Doesn't work when the range gets down to 1 element; that "mid + 1" part could end up reading outside of the array.

You should decide whether your endpoints are inclusive or exclusive. Using [start, end) instead of [start, end] makes these sorts of things a lot simpler, IMO.
 

stickboy

Ars Tribunus Angusticlavius
6,218
Subscriptor
Whee. Here's my code:
Code:
static void*
my_bsearch(const void* key, const void* base,
           size_t nmemb, size_t size,
           int (*compar)(const void*, const void*))
{
   size_t low = 0; // Inclusive.
   size_t high = nmemb; // Exclusive.

   while (low < high) {
      size_t mid = (low + high) / 2;
      const unsigned char* bytes = base;
      const void* item = bytes + mid * size;
      int ret = compar(key, item);
      if (ret == 0) {
         return item;
      } else if (ret < 0) {
         high = mid;
      } else if (ret > 0) {
         low = mid + 1;
      }
   }
   return NULL;
}
 
9 out of 10 programmers can't perfectly implement binary search on their first try because 1 out of 10 programmers doesn't know that his language of choice has a built-in binary search function in its standard library. ;)

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.

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... or professional programmers writing J2EE applications for major enterprises, and don't understand how locks, mutexs, and synchronization work... :scared:
 

norton_I

Ars Tribunus Angusticlavius
6,172
Subscriptor++
I wasn't confident that I could get an iterative approach right on the first try, so I did a recursive implementation. It seems to work.

Code:
int *my_bsearch(int element, int *list, size_t length)
{
    size_t mp;

    if(length == 1) {
        if(element == *list)
            return list;
        else
            return 0;
    }
    mp = length / 2;
    if(list[mp] == element)
        return list+mp;
    if(list[mp] > element)
        return my_bsearch(element, list, mp);
    if(list[mp] < element)
        return my_bsearch(element, list+mp, length-mp);
}
 
First attempt in C (well, C99) worked without bugs. Ironically though, there was a bug in the first version of my verification code.
Code:
#include <stddef.h>

const double *bsearch(const double *tbl,size_t n,double v) {
    const double *a=tbl;
    const double *b=tbl+n;

    while (b>a) {
        const double *p=a+(b-a)/2;
        if (*p>v) b=p;
        else if (*p<v) a=p+1;
        else return p;
    }
    return 0;
}

Test code:
Code:
#include <stdio.h>

int main() {
    const size_t maxt=5;
    double base=0.3,step=0.7;
    double arr[maxt];

    for (int n=0;n<maxt;++n) {
        for (int i=0;i<n;++i) arr[i]=base+step*i;
        for (int i=0;i<n;++i) {
            double t=arr[i];
            printf("test A, member %d of %d test: %s\n",
                   i+1,n,(bsearch(arr,n,t)==arr+i)?"pass":"fail");
        }
        printf("test A, < min of %d test: %s\n",
               n,(bsearch(arr,n,base-step*0.5)==0)?"pass":"fail");
        printf("test A, > max of %d test: %s\n",
               n,(bsearch(arr,n,base+step*(n+0.5))==0)?"pass":"fail");
        for (int i=0;i<n-1;++i) {
            double t=arr[i]+step*0.5;
            printf("test A, member %d+ of %d test: %s\n",
                   i+1,n,(bsearch(arr,n,t)==0)?"pass":"fail");
        }
    }

    // test B: with duplicates in array
    for (int n=0;n<maxt;n+=2) {
        for (int i=0;i<n-1;i+=2) arr[i]=arr[i+1]=base+step*i;
        for (int i=0;i<n;++i) {
            double t=arr[i];
            const double *p=bsearch(arr,n,t);
            printf("test B, member %d of %d test: %s\n",
                   i+1,n,(p && *p==t)?"pass":"fail");
        }
        printf("test B, < min of %d test: %s\n",
               n,(bsearch(arr,n,base-step*0.5)==0)?"pass":"fail");
        printf("test B, > max of %d test: %s\n",
               n,(bsearch(arr,n,base+step*(n+0.5))==0)?"pass":"fail");
        for (int i=0;i<n-1;++i) {
            double t=arr[i]+step*0.5;
            printf("test B, member %d+ of %d test: %s\n",
                   i+1,n,(bsearch(arr,n,t)==0)?"pass":"fail");
        }
    }
}
 

Alamout

Ars Legatus Legionis
27,285
First attempt did not handle the empty sequence correctly...for some reason I didn't think that seq[0] would be out of range. :rolleyes:

norton: I'm guessing your code doesn't handle length 0 very well, but maybe I'm just not reading it right.

aliftedlorax: luckily Python handles arbitrary integers and I don't have to worry about that one. :D edit: and I can't store a sequence that long anyway!

Code:
def bin_search(seq, t):
    '''Returns i where seq[i] == t, or None'''

    lo = 0
    hi = len(seq) - 1

    # this code should have existed...
    #if not seq:
        #return None

    if seq[lo] == t:
        return lo
    elif hi <= lo:
        return None
    elif seq[hi] == t:
        return hi
    elif seq[lo] > t or seq[hi] < t:
        return None

    while lo < (hi - 1):
        mid = (lo + hi) / 2
        if seq[mid] == t:
            return mid
        elif seq[mid] < t:
            lo = mid
        elif seq[mid] > t:
            hi = mid
        else:
            return None

    # end game: lo == hi or lo == hi - 1
    if seq[lo] == t:
        return lo
    elif hi <= lo:
        return None
    elif seq[hi] == t:
        return hi
    else:
        return None

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.
 
Alamout":z7v96tf6 said:
First attempt did not handle the empty sequence correctly...for some reason I didn't think that seq[0] would be out of range. :rolleyes:
Well, the binary search should fail on an empty sequence. The question is, what's the most informative way to fail? Probably not an out of bounds error (or worse in C, an out of bounds memory access).
 

Vince-RA

Ars Praefectus
5,521
Subscriptor++
My first thought was, "what the fuck, I've been writing stupid-ass web and business process code for the better part of the last decade, and I bet I could still do that!" My second thought was, "shit, can I really do that still?!?".

This took about 20 minutes and more head scratching over the midIndex + 1 than I'd prefer to admit, but I think it works. I suspect I could eliminate the "else if" condition by being a little more clever, but hey, I've only had one cup of coffee today. This is in C# (Edit: and I know it will fail if array.GetLowerBound(0) + array.GetUpperBound(0) is greater than MaxInt - if it's good enough for the JDK, it's good enough for me! :p):

Code:
/// <summary>
        /// Perform a binary search on a sorted integer array
        /// </summary>
        /// <param name="target">Value to search for</param>
        /// <param name="array">Array sorted in ascending order, duplicate values permitted</param>
        /// <returns>Returns -1 if target not found in array; target value otherwise</returns>
        static int BinarySearch(int target, int[] array, int lowerIndex, int upperIndex)
        {
            if (array.Length == 0)
            {
                return -1;
            }
            else if ((upperIndex - lowerIndex) == 0)
            {
                return (array[lowerIndex] == target ? target : -1);
            }
            else
            {
                int midIndex = (lowerIndex + upperIndex) / 2;
                if (array[midIndex] > target)
                {
                    return BinarySearch(target, array, lowerIndex, midIndex);
                }
                else if (array[midIndex] < target)
                {
                    return BinarySearch(target, array, midIndex + 1, upperIndex);
                }
                else
                {
                    return target;
                }
            }
        }

Edit again: OK, this was a boneheaded way to do it. It'll only work if the array to be searched contains non-negative integers. Probably should have made the function return a bool instead. Ah well. Hello, 90%!
 

chirpflare

Ars Scholae Palatinae
1,328
newwb":34ukp5nh said:
aliftedlorax":34ukp5nh said:
Extra Extra, Read All About It: Nearly All Binary Searches and Mergesorts Are Broken -- Josh Bloch

edit: looks like commenters on the original blog post thought of the same thing...
Holy crap, the comments below that article could feed The Daily WTF for a month!

I love how loads of people are saying its easy and it only took them ten minutes, but even a cursory glance shows many would fail on large/empty arrays or where the target isn't in the array, let alone more obscure bugs.

This is kind of a silly exercise, though. It's not important for people to write bug-free code on the first try.

The bit about not running it against tests first is a bit daft, but still, you only have to read a few comments in the article to see lots of evidence people's misplaced confidence in their code. In that sense I think its a really interesting experiment, I might offer it up as a test at work, assuming its not been read too much already!
 

FogleBird

Ars Tribunus Militum
2,237
w00t, got it on my first try. (Python)

Code:
def binary_search(array, value):
    a = 0
    b = len(array) - 1
    while True:
        if b < a:
            break
        m = (b - a) / 2 + a
        if array[m] == value:
            return m
        elif array[m] > value:
            b = m - 1
        else:
            a = m + 1
    return -1
Edit 1: Not sure why I didn't just put while a <= b, but meh, it works.
Edit 2: Took me 7 minutes to write according to Eclipse local history.
 

sbarnabas

Wise, Aged Ars Veteran
130
stickboy":96n23oyf said:
sbarnabas":96n23oyf said:
I didn't bother to test this, but it seems correct (doesn't it always?)... C#, recursive (because I figure the CLR can do TCO better than I can):
Doesn't work when the range gets down to 1 element; that "mid + 1" part could end up reading outside of the array.

You should decide whether your endpoints are inclusive or exclusive. Using [start, end) instead of [start, end] makes these sorts of things a lot simpler, IMO.

I assumed bounds were inclusive:
Code:
 search(mylist, 0, mylist.Length-1 , key);
would be how you call it.

It does work for a range of 1 in that case because when mid+1 is outside the bounds of the array, the recursive call finds that start > end and returns -1. I only ever read from mid, which (if start<=end) should always be within the bounds of the array (because end-start will always be non-negative, and end starts out inclusive and is monotonically decreasing in the recursive calls). That was one reason I did end-(end-start)/2...much easier to convince myself it won't do an out of bounds index.

Using inclusive bounds also neatly sidesteps the problem of an empty collection, imo.
 

kenada

Ars Legatus Legionis
17,589
Subscriptor
Here is some (probably unidiomatic) Ruby. So untested that I didn’t even check for syntax errors. :D

Code:
def bsearch(arr, val)
  return nil if arr.length = 0
  pos = arr.length / 2
  case val <=> arr[pos]
    when -1 then bsearch(arr[0..(pos-1)], val)
    when 0 then pos
    when 1 then bsearch(arr[(pos+1)..-1], val)
  end
end

Edit: Durr. That should be “return nil if arr.length = 0”. Oh well.
Edit 2: Return the position when the value is found because return the value is not particularly useful. :eek:
 

HL7

Ars Praefectus
3,523
Subscriptor++
I saw someone already did C#, so I did VB. You can break it by calling it with out-of-bound indices, but that didn't seem to be a condition of the test so I didn't bother to check.

It worked perfectly on the first try:
Code:
Function BSearch(Of T As IComparable)(ByVal SearchArray() As T, ByVal Key As T, ByVal StartIndex As Integer, ByVal EndIndex As Integer) As T
        If StartIndex > EndIndex Then
            Return Nothing
        End If

        Dim MidIndex As Integer = StartIndex + (EndIndex - StartIndex) \ 2
        Dim Middle As T = SearchArray(MidIndex)

        Select Case Key.CompareTo(Middle)
            Case Is < 0
                Return BSearch(SearchArray, Key, StartIndex, MidIndex - 1)

            Case 0
                Return Key

            Case Is > 0
                Return BSearch(SearchArray, Key, MidIndex + 1, EndIndex)
        End Select

    End Function
 

Alamout

Ars Legatus Legionis
27,285
FogleBird":1mizycdz said:
w00t, got it on my first try. (Python)

(code)

Edit 1: Not sure why I didn't just put while a <= b, but meh, it works.
Edit 2: Took me 7 minutes to write according to Eclipse local history.
Hm, that's a much nicer version. Incrementing/decrementing the midpoint (which is an obvious thing to do in retrospect) makes the comparison step, and the break condition, much simpler.
 

HL7

Ars Praefectus
3,523
Subscriptor++
stickboy":1tfwkhv3 said:
sbarnabas":1tfwkhv3 said:
It does work for a range of 1 in that case because when mid+1 is outside the bounds of the array, the recursive call finds that start > end and returns -1.
Oops, you're right. Sorry.

Your cmp checks are backwards, though. ;)
I think his checks are right -- he did array[mid].CompareTo(item), and in the case that's less than 0, that means to search the upper part of the array -- which he did. His checks are essentially the reverse of mine.
 

crxs

Ars Tribunus Militum
2,587
Subscriptor
This seems to be working (Java). I didn't get it right on the first try, I had startindex < endIndex in the while condition, but I *meant* smaller or equal. It took me about 10 minutes which included a few mental debugging runs. I didn't spot the bug in the while condition because I meant the correct thing and mentally followed what I meant instead of what I wrote.
Code:
public static int binarySearchForIndex(int[] ascOrderedArray, int searchValue)
	{
		int startIndex = 0;
		int endIndex = ascOrderedArray.length-1;
		
		while (startIndex <= endIndex)
		{
			//take middle element and compare to search Value
			int middle = startIndex + ((endIndex - startIndex) / 2);
			if (ascOrderedArray[middle] == searchValue)
			{
				return middle;
			}
			else if (ascOrderedArray[middle] < searchValue)
			{
				//if element is smaller than search value then search value is in second half
				startIndex = middle + 1;
			}
			else 
			{
				//if element is larger than search value then search value is in first half
				endIndex = middle - 1;
			}
		}
		return -1;
	}

Edit to add:
Actually I think there is more to be learned about programmers by looking at what they do after they are done with implementing this. Do they write test calls to see what results the function returns, and how much do their test calls cover? I checked searching for the first element and the last one (this caught my bug), the middle one, one that is bigger than the biggest element, two that exist at random locations in the array and one that doesn't exist and is between two array values. Additionally I should have checked an empty array and one consisting of only one element.
 

HL7

Ars Praefectus
3,523
Subscriptor++
crxs":3oxsyivv said:
Actually I think there is more to be learned about programmers by looking at what they do after they are done with implementing this. Do they write test calls to see what results the function returns, and how much do their test calls cover?
Personally, I set up a sorted Integer array containing the numbers 1-9. I ran a loop from -5 to 15, calling BSearch for each. I didn't see any point in testing a single-element array, because my function is recursive and the single-element test case was hit during one of those searches.
 

Fink_Ployd

Ars Tribunus Militum
2,748
HL7":2wn5qmjx said:
crxs":2wn5qmjx said:
Actually I think there is more to be learned about programmers by looking at what they do after they are done with implementing this. Do they write test calls to see what results the function returns, and how much do their test calls cover?
Personally, I set up a sorted Integer array containing the numbers 1-9. I ran a loop from -5 to 15, calling BSearch for each. I didn't see any point in testing a single-element array, because my function is recursive and the single-element test case was hit during one of those searches.

If you're writing production software (I probably wouldn't have done more for this) - if your testing is to be worth anything, you have to test the corner cases. What happens when there's multiple equal values - which one does your search find? What if it's not found, and all the values in the array are greater than your search value? Less than?

Corner cases, corner cases, corner cases.
 

HL7

Ars Praefectus
3,523
Subscriptor++
Fink_Ployd":yhu0yrgf said:
If you're writing production software (I probably wouldn't have done more for this) - if your testing is to be worth anything, you have to test the corner cases. What happens when there's multiple equal values - which one does your search find? What if it's not found, and all the values in the array are greater than your search value? Less than?

Corner cases, corner cases, corner cases.
In my particular implementation, the case of multiple equal values is irrelevant -- the function returns the key itself if the key is found. I did it this way because the specification was vague -- it didn't say whether to return the index of the first occurrence, the index of any occurrence, a boolean indicating whether the key was found, or what. So I did it in what I thought was the simplest way -- return the key if it's found, and Nothing if the key isn't found. It doesn't tell you where the key is in the array, only that it's there. It could easily be modified to return an index, but requiring the index of the first occurrence would change the algorithm. This highlights the importance of good specifications -- if your specification is vague, you'll get programmers making decisions that may not be what you wanted.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Alamout":pzpobu17 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.
 

lostnihilist

Ars Scholae Palatinae
1,436
are there mistakes here? I didn't find any. I missed catching the IndexError first time around (empty list), but otherwise it is the same as my first final draft (before testing). I didn't open an interpreter to play with it, but I did follow through the code with pencil and paper first.

Code:
def binary_search(ele, list_, pre_index=0):
    index = len(list_) // 2
    try:
        mid = list_[index]
    except IndexError:
        return None
    if index == 0 and ele != mid:
        return None
    elif ele == mid:
        return index + pre_index
    else:
        try:
            if ele < mid:
                return binary_search(ele, list_[:index], 0) + pre_index
            else:
                return binary_search(ele, list_[index:], index) + pre_index
        except TypeError:
            return None

and my test cases:

Code:
>>> l = range(-2,3)
>>> [binary_search(i, l) for i in range(-4,5)]
[None, None, 0, 1, 2, 3, 4, None, None]
>>> binary_search(-1.2, l)
>>> binary_search(0.5, l)
>>> binary_search(0.5, [])
>>>

edit: Is there something wrong with me that I've never taken a CS class, but I still write algo's like this recursively? I didn't even think of doing a while loop.
 

sbarnabas

Wise, Aged Ars Veteran
130
Richard Berg":2lfch2rz said:
Csc.exe tells me that my answer doesn't even compile. Take/Skip return vanilla IEnumerables. What I really want is an IImmutableList(Of T) that has appropriate LINQ overloads. Until I find/write such a thing, I'll just stare at the Ruby solution with envy...

Can't you just do .ToList() on your IEnumerables? I think you have another bug too, though...if your key value is greater than the maximal element in the list, your code will return the max value of the list (because you return -1 from the recursive call...then add midpoint+1 on the way up)
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Can't you just do .ToList() on your IEnumerables?
Sure, if you don't mind making your binary search O(N).

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)
 

johncch

Smack-Fu Master, in training
95
Not sure if this is bug free, but it pretty much tested okay for some of the terms i threw at it. The code is compilable and runnable. C&C welcomed. Bugs mostly in language quirks and misunderstanding some of the Api used, such as List.slice, which has an exclusive end boundary, while sensible but probably rarer in other languages. Interesting.

Edit: Oh craps, (bug,) I assumed search list is not empty. Bummers.

In Scala:

Code:
/**
 * Welcome to the Binary Search Application written to prove I'm
 * in the top 10% of all programmers lulz
 *
 * @author johncch
 */

object BSearch {
	var searchArray = List("Most","programmers","think","that","with","the","above","description","in","hand","writing","code","is","easy","they're","wrong","only","way","you'll","believe","by","putting","down","this","column","right","now","and","yourself","Try","it")

	def bsearch(term:String, list:List[String], order:Int){
		val pivot:Int = list.length / 2
		println("searching in " + list);
		println("result is : " + list(pivot) + " ?== " + term + " is " + (list(pivot) == term ))
		(list(pivot) == term) match {
				case true => println("found " + term + " in order " + order)
				case false if list.length > 1 => (term < list(pivot)) match {
						case true => bsearch(term, list.slice(0, pivot), order + 1)
						case false => bsearch(term, list.slice(pivot + 1, list.length), order + 1)
				}
				case false => println("The term " + term + " is not found after " + order + " orders.")
		}
	}

	def main(args:Array[String]) {
		println("Welcome to the small binary search application")

		if(args.length != 1) {
			println("This program requires one search term")
			return
		}
		
		val searchTerm = args(0)

		searchArray = searchArray.map(_.toLowerCase).sort(_ < _);
		println("Searching " + searchTerm + " from " + searchArray);

		bsearch(searchTerm, searchArray, 1);
	}
}
 
I thought I'd do a functional one for fun, in Haskell.

This one (unlike my C version) works with a closed interval and is recursive. It also worked first go, though having done it once, I guess it's not too hard to do it again. I think the key thing is a consideration of the invariants — if one has a good set of invariants, one can formally verify the behaviour, and one can visually check the code to ensure those invariants are satisfied if it's not too complicated (such as for binary search).

Code:
Code:
import Array

bsearch v arr = bsearch' v a b arr where (a,b) = bounds arr
bsearch' v a b arr | a > b = Nothing
                   | otherwise = let p = div (a+b) 2 in
                                 case compare (arr ! p) v of
                                 EQ -> Just p
                                 LT -> bsearch' v (p+1) b arr
                                 GT -> bsearch' v a (p-1) arr

Verification code:
Code:
testvals []     = [0]
testvals (a:as) = (a-1):tv' (a:as)
                  where tv' [a] = [a,a+1]
                        tv' (a:b:as) | a /= b = a:(a+b)/2:tv' (b:as)
                                     | a == b = tv' (b:as)

bsVerify f v arr  = case f v arr of
                    Just i  -> arr ! i == v
                    Nothing -> not $ elem v (elems arr)

bsReport (v,arr) = (if ok then "pass: " else "fail: ") ++ show v ++ ", " ++ show (elems arr)
                   where ok = bsVerify bsearch v arr

main = mapM_ (putStrLn . bsReport) $
       concatMap (\ns -> [(v,listArray (1,length ns) ns) | v <- testvals ns]) $
       [[1..k] | k <- [0..5]] ++ [concat [[i,i] | i<- [1..k]] | k <- [0..5]]
 
Status
Not open for further replies.