0% found this document useful (0 votes)
18 views

Binary Search

Uploaded by

akurathikotaiah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Binary Search

Uploaded by

akurathikotaiah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Binary Search

#include <stdio.h>
int binarySearch(int arr[], int size, int target)
{
int left = 0;
int right = size - 1;

while (left <= right)


{
int mid = left + (right - left) / 2;

if (arr[mid] == target)
{
return mid; // Element found, return its index
}
else if (arr[mid] < target)
{
left = mid + 1; // Search the right half
}
else
{
right = mid - 1; // Search the left half
}
}

return -1; // Element not found


}

main()
{
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 7;

int result = binarySearch(arr, size, target);


clrscr();
if (result != -1)
{
printf("Element %d found at index %d\n", target, result);
}
else
{
printf("Element %d not found in the array\n", target);
}

getch();
}

Binary Search using Two Pointers


#include <stdio.h>

int binarySearch(int arr[], int size, int target)


{
int *left = arr;
int *right = arr + size - 1; // Pointer to the last element

while (left <= right)


{
int *mid = left + (right - left) / 2;

if (*mid == target)
{
return mid - arr; // Element found, return its index
}
else if (*mid < target)
{
left = mid + 1; // Search the right half
}
else
{
right = mid - 1; // Search the left half
}
}

return -1; // Element not found


}

main()
{
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int result = binarySearch(arr, size, target);
clrscr();
if (result != -1)
{
printf("Element %d found at index %d\n", target, result);
}
else
{
printf("Element %d not found in the array\n", target);
}

getch();
}

You might also like