Run ❯
Get your
own
website
×
Change Orientation
Change Theme, Dark/Light
Go to Spaces
Python
C
Java
def binarySearch(arr, targetVal): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == targetVal: return mid if arr[mid] < targetVal: left = mid + 1 else: right = mid - 1 return -1 myArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] myTarget = 15 result = binarySearch(myArray, myTarget) if result != -1: print("Value",myTarget,"found at index", result) else: print("Target not found in array.") #Python
#include
int binarySearch(int arr[], int size, int targetVal); int main() { int myArray[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int myTarget = 15; int size = sizeof(myArray) / sizeof(myArray[0]); int result = binarySearch(myArray, size, myTarget); if (result != -1) { printf("Value %d found at index %d\n", myTarget, result); } else { printf("Target not found in array.\n"); } return 0; } int binarySearch(int arr[], int size, int targetVal) { int left = 0; int right = size - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == targetVal) { return mid; } if (arr[mid] < targetVal) { left = mid + 1; } else { right = mid - 1; } } return -1; } //C
public class Main { public static void main(String[] args) { int[] myArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int myTarget = 15; int result = binarySearch(myArray, myTarget); if (result != -1) { System.out.println("Value " + myTarget + " found at index " + result); } else { System.out.println("Target not found in array."); } } public static int binarySearch(int[] arr, int targetVal) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == targetVal) { return mid; } if (arr[mid] < targetVal) { left = mid + 1; } else { right = mid - 1; } } return -1; } } //Java
Python result:
C result:
Java result:
Value 15 found at index 7
Value 15 found at index 7
Value 15 found at index 7