Binary Search in an Sorted Array - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Binary Search in an Sorted Array

Share This
Binary search is a powerful search algorithm designed for sorted lists. It works by repeatedly dividing the list in half and eliminating the half that couldn't possibly contain the target element.
 
This significantly reduces the number of comparisons needed to find the element, especially in very large datasets.
 
The importance of binary search stems from its efficiency. Unlike linear search, which examines each element in the list one by one, binary search cuts the search space in half with each iteration. This results in a time complexity of O(log n), where n is the number of elements. This logarithmic complexity means that the search time increases very slowly as the data size grows, making it ideal for large sorted collections.
 
Binary search is not only efficient but also relatively simple to implement and understand. This makes it a versatile tool applicable in various situations. From searching large phone directories to finding specific records in sorted databases, binary search plays a crucial role in optimizing search operations across computer science and information retrieval applications.
Source Code
#include<stdio.h> #include<stdlib.h> int main() { int n, key; int i, index = -1, left, right, mid; int *p; printf("Enter the number of inputs:"); scanf("%d", &n); p = (int *)malloc(n * sizeof(int)); printf("Enter the values :"); for (i = 0; i < n; i++) { scanf("%d", &p[i]); } printf("Enter the key (which will be searched):"); scanf("%d", &key); left = 0; right = n; while (left <= right) { mid = (left + right) / 2; if(p[mid] == key) { index = mid; break; } else if(p[mid] < key) left = mid + 1; else right = mid - 1; } if(index == -1) printf("The key not found!\n"); else printf("The key is present at index %d !\n", index); return 0; }




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.