Alex M

Alex M

  • NA
  • 3
  • 2k

How do i prevent stack overflows in binary search algorithm?

Apr 28 2019 2:12 PM
I'm using the following c# binary search algorithm to search for doubles in a double array containing 256 - 4096 elements:
  1. public static void Search(double[] array, double key)     
  2.         {  
  3.             Quicksort.Sort(array);  
  4.             int min = 0;  
  5.             int max = array.Length - 1;  
  6.             bool found = false;  
  7.   
  8.             while (min <= max)  
  9.             {  
  10.                 int mid = (min + max) / 2;  
  11.   
  12.                 if (array[mid] == key)  
  13.                 {  
  14.                     found = true;  
  15.                     Console.WriteLine($"{key} was found at index {mid} of the array");  
  16.                 }  
  17.                 else if (array[mid] > key)  
  18.                     max = mid - 1;  
  19.                 else if (array[mid] < key)  
  20.                     min = mid + 1;  
  21.             }  
  22.             if (found == false)  
  23.                 Console.WriteLine($"{key} wasn't found in the array.");  
 When i try to run it, i get a stack overflow exception thrown... How do i fix it?
 
Thanks for the help! 

Answers (2)