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

Binary Search

Uploaded by

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

Binary Search

Uploaded by

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

#include <stdio.

h>

void binarySearch(int *arr, int size, int target) {


int *beg = arr; // Pointer to the beginning of the array
int *end = arr + size - 1; // Pointer to the end of the array
int *mid;

while (beg <= end) {


mid = beg + (end - beg) / 2; // Calculate the mid pointer

if (*mid == target) {
printf("Element %d found at position %ld\n", target, mid - arr);
return;
} else if (*mid < target) {
beg = mid + 1; // Move the beg pointer to mid + 1
} else {
end = mid - 1; // Move the end pointer to mid - 1
}
}

printf("Element %d not found\n", target);


}

int main() {
int n, target;

// Take the size of the array as input


printf("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n];

// Take the array elements as input


printf("Enter %d elements in ascending order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Take the target element as input


printf("Enter the element to search for: ");
scanf("%d", &target);

// Perform binary search


binarySearch(arr, n, target);

return 0;
}

You might also like