Skip to content

Instantly share code, notes, and snippets.

@SaberZA
Last active September 30, 2016 08:22
Show Gist options
  • Select an option

  • Save SaberZA/d16513c975b62c8c931fe98eb363bc02 to your computer and use it in GitHub Desktop.

Select an option

Save SaberZA/d16513c975b62c8c931fe98eb363bc02 to your computer and use it in GitHub Desktop.
Recursive Binary Search
private static void MovieSearch2()
{
string[] movies = new string[] { "Dumb and Dumber", "Final Destination", "Rocky", "Speed", "The Notebook" };
int recursivePosition = RecursiveBinarySearch("rocky", movies, 0, movies.Length - 1);
Console.WriteLine(recursivePosition);
}
private static int RecursiveBinarySearch(string searchString, string[] items, int low, int high)
{
if (low > high) return -1; // Base Case
var mid = (high + low) / 2;
var guess = items[mid];
if (Compare(searchString, guess) == 0) // Case where item is found
return mid;
if (Compare(searchString, guess) > 0) // Case when search down left side of array
return RecursiveBinarySearch(searchString, items, low, mid - 1);
return RecursiveBinarySearch(searchString, items, mid + 1, high); // Case when search down right side of array
}
private static int Compare(string searchString, string guess)
{
return String.Compare(guess, searchString, StringComparison.OrdinalIgnoreCase);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment