Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views2 pages

Experiment - 9B AIM Theory

The document describes an experiment to perform binary search, an efficient algorithm for finding an element's position in a sorted array with a time complexity of O(log n). It includes a C code implementation of the binary search function and an example usage that searches for a target element in a predefined array. The result confirms that the binary search has been successfully implemented.

Uploaded by

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

Experiment - 9B AIM Theory

The document describes an experiment to perform binary search, an efficient algorithm for finding an element's position in a sorted array with a time complexity of O(log n). It includes a C code implementation of the binary search function and an example usage that searches for a target element in a predefined array. The result confirms that the binary search has been successfully implemented.

Uploaded by

bro665444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

EXPERIMENT – 9B

AIM To perform binary search

THEORY

Binary search is another algorithm for searching. Perhaps the most efficient algorithm. Binary search
is a searching algorithm used to find an element's position in a sorted array. It works by repeatedly
dividing in half the portion of the array that could contain the element, until you've narrowed down
the possible locations to just one. This algorithm works efficiently with sorted arrays and has a time
complexity of O(log n).

C CODE

#include <stdio.h>

// Function to perform binary search

int binarySearch(int arr[], int left, int right, int target) {

while (left <= right) {

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

// Check if target is present at mid

if (arr[mid] == target)

return mid;

// If target greater, ignore left half

if (arr[mid] < target)

left = mid + 1;

// If target is smaller, ignore right half

else

right = mid - 1;

// If target is not found in array

return -1;

}
int main() {

int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};

int n = sizeof(arr) / sizeof(arr[0]);

int target = 23;

int result = binarySearch(arr, 0, n - 1, target);

if (result == -1)

printf("Element is not present in array\n");

else

printf("Element is present at index %d\n", result);

return 0;

OUTPUT

RESULT

Binary search has been implemented in arrays.

You might also like