Last active
December 29, 2023 20:58
-
-
Save HamidMolareza/27efe4a8607f4787bb03dbd82b20f69d to your computer and use it in GitHub Desktop.
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
from typing import List | |
def binary_search(numbers: List[int], target: int) -> bool: | |
""" | |
Perform binary search to check if the target exists in the sorted list. | |
:param numbers: A sorted list of integers. | |
:param target: The integer to search for. | |
:return: True if the target exists, False otherwise. | |
""" | |
start = 0 | |
end = len(numbers) - 1 | |
while start <= end: | |
mid = (start + end) // 2 | |
if target == numbers[mid]: | |
# Target found at the middle index. | |
return True | |
elif target < numbers[mid]: | |
# Target is in the left half. | |
end = mid - 1 | |
else: # target > numbers[mid] | |
# Target is in the right half. | |
start = mid + 1 | |
# Target not found. | |
return False |
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
static int BinarySearch(IReadOnlyList<int> array, int target) | |
{ | |
// Initialize left and right pointers for the binary search | |
int left = 0; | |
int right = array.Count - 1; | |
// Continue the search until the left pointer exceeds the right pointer | |
while (left <= right) | |
{ | |
// Calculate the middle index | |
int mid = left + (right - left) / 2; | |
// Check if the middle element is the target | |
if (array[mid] == target) | |
{ | |
// Target found, return the index | |
return mid; | |
} | |
// If the target is greater than the middle element, search the right half | |
if (array[mid] < target) | |
{ | |
left = mid + 1; | |
} | |
// If the target is smaller than the middle element, search the left half | |
else | |
{ | |
right = mid - 1; | |
} | |
} | |
// Target not found in the array | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment