Created
November 7, 2023 19:36
-
-
Save tcortega/e38026eafcb4c0e78a5c15bbbfb4c76c to your computer and use it in GitHub Desktop.
This file contains 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
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23 }; | |
var list = new List<int>(input); | |
foreach (var n in input) | |
{ | |
var actualIndex = list.IndexOf(n); | |
var foundIndex = FindAt(input, n, 0, input.Length - 1); | |
Console.WriteLine($"[{n}] Expected: {actualIndex} | Found: {foundIndex}"); | |
} | |
return; | |
// Binary search algorithm assuming that the array is sorted in ascending order. | |
int FindAt(int[] numbers, int number, int startPosition, int endPosition) | |
{ | |
if (numbers[0] > number) return -1; | |
if (numbers[^1] < number) return -1; | |
var middlePos = startPosition + (endPosition - startPosition) / 2; | |
if (numbers[middlePos] == number) return middlePos; | |
if (numbers[middlePos] > number) | |
{ | |
return FindAt(numbers, number, startPosition, middlePos - 1); | |
} | |
return FindAt(numbers, number, middlePos + 1, endPosition); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment