0% found this document useful (0 votes)
3 views1 page

Binary Search

Uploaded by

Yashi Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Binary Search

Uploaded by

Yashi Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy