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

Binary Search

HJzokznznsksksksnskdididkdjdjdndjdjdjkddod

Uploaded by

santoshallu1234
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)
18 views

Binary Search

HJzokznznsksksksnskdididkdjdjdndjdjdjkddod

Uploaded by

santoshallu1234
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

// Binary Search

#include <stdio.h>

// Binary search algorithm (works only on sorted arrays)


int binarySearch(int arr[], int n, int x) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x)
return mid; // Return index if element is found
else if (arr[mid] < x)
left = mid + 1; // Search in the right half
else
right = mid - 1; // Search in the left half
}
return -1; // Return -1 if element is not found
}

int main() {
int arr[100], n, x;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

printf("Enter the elements of the array in sorted order:\n");


for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);

printf("Enter the element to search: ");


scanf("%d", &x);

int index = binarySearch(arr, n, x);


if (index != -1)
printf("Element found at index %d\n", index);
else
printf("Element not found\n");

return 0;
}

Binary search is a search algorithm used to find the position of a target value
within a sorted array. Here's a complexity analysis of binary search:

Time Complexity: Binary search has a time complexity of O(log n), where n is the
number of elements in the array. This is because, in each step of the algorithm,
the search space is divided in half. As a result, the algorithm eliminates half of
the remaining elements at each step, leading to a logarithmic time complexity.
Binary search is efficient for large datasets because its time complexity grows
slowly with increasing input size.
Space Complexity: Binary search has a space complexity of O(1), meaning that it
requires a constant amount of extra space regardless of the size of the input
array. This is because the algorithm only needs a few variables to keep track of
the indices and values during its execution, and it does not require any additional
data structures or memory allocations.

You might also like