Skip to main content

Posts

Showing posts with the label sorted

What is wrong with my code - circularly sorted array does not show any results

I had an interview today and the person asked me this question: How do you find easily an item in a circularly sorted array Since I didn't know the answer, I tried to find a solution. Here's what I have: Thanks <?php function searchincircularsorterlist($a, $len, $num) { $start=0; $end=$len-1; $mid = 0; while($start<$end) { $mid=$start+$end/2; if ($num == $a[$mid]) { return $num; } if($num<$a[$mid]) { if($num<$a[$start] && $a[$start]<=$a[$start+1]) $start=$mid++; else $end=$mid--; } else { if($num>$a[$end] && $a[$end-1]<=$a[end]) $end=$mid--; else $start=$mid++; } } if ($start == $end && $num == $a[$start]) { return $num; } return -1; } $array = array(7,8,9,0,1,2,3,4,5,6); var_dump(searchincircularsorterlist($array,sizeof(