Last active
September 30, 2016 08:22
-
-
Save SaberZA/d16513c975b62c8c931fe98eb363bc02 to your computer and use it in GitHub Desktop.
Recursive Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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