News for hackers. Stuff that matters.
Re:Are you one of the 10% of programmers who can write a bin... by ohashi on Monday April 19, 2010 @06:57PM (#1278105)
I wrote my version in PHP, wondering if someone could tell me what I did wrong (I didn't test it, I assume there are mistakes).

  <?php
  function bsearch($search, $array, $start, $end){
      //$start cannot be zero.
      //$search not in $array
      if($start>$end){
          return -1;
      }
      //calculate middle
      $middle = $start + ceil(($end-$start)/2);
      //check match
      if($array[$middle]==$search){
          return $middle;
      }
      //is the middle higher than the search, if so, cut top
      else if($array[$middle]>$search){
          return bsearch($search, $array, $start, $middle-1);
      }
      //otherwise cut bottom
      else{
          return bsearch($search, $array, $middle+1, $end);
      }
  }

  ?>
Re:Are you one of the 10% of programmers who can write a bin... by gizmo on Monday April 19, 2010 @07:11PM (#1278126)
Yup, no sigar.

1. You get a division by zero when $start == $end

2. When the element $search doesn't exist your program breaks

3. You always check array for value $middle, so $middle should have the range 0 <= $middle < length($array). But according to the comment $start cannot be zero. If so, then $middle is always larger than zero, and as such, the first element of the array is never considered.

So it's pretty buggy.

Re:Are you one of the 10% of programmers who can write a bin... by ohashi on Monday April 19, 2010 @07:31PM (#1278158)
1. i knew there was issue with start==end. what is the solution for that issue? i had originally written $start<=$end

2. i think this is connected to previous issue, with ending it

3. I knew the zero thing would be an issue, but... had to write it before caps game started :(