Created
April 14, 2025 03:35
-
-
Save UltiRequiem/0f953a731975ec774fbb385cbffb6aa7 to your computer and use it in GitHub Desktop.
Simple binary Search
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
#include <iostream> | |
using std::cout, std::endl; | |
int binarySearch(int *haystack, int size, int needle) | |
{ | |
int low = 0; | |
int high = size - 1; | |
while (low <= high) | |
{ | |
int mid = (low + high) / 2; | |
if (haystack[mid] == needle) | |
{ | |
return mid; | |
} | |
if (haystack[mid] > needle) | |
{ | |
high = mid - 1; | |
} | |
else | |
{ | |
low = mid + 1; | |
} | |
} | |
return -1; | |
} | |
int main() | |
{ | |
int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; | |
int numbersSize = sizeof(numbers) / sizeof(numbers[0]); | |
cout << "Value found at index " << binarySearch(numbers, numbersSize, 9) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment