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

Program 8

Program

Uploaded by

nagowtham5
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)
2 views

Program 8

Program

Uploaded by

nagowtham5
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

//Program 8: Develop C program to search for a key element in an array of ‘n’

elements using binary seach.

#include <stdio.h>

int main()
{
int n, key, low, high, mid, i;

// Input the number of elements in the array


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

int array[n];

// Input the elements of the array


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

// Input the key to search


printf("Enter the key to search: ");
scanf("%d", &key);

// Initialize low and high indices


low = 0;
high = n - 1;

// Perform binary search


while (low <= high)
{
mid = (low + high) / 2;

if (array[mid] == key)
{
printf("Key %d found at position %d.\n", key, mid + 1);
return 0;
}
else if (array[mid] < key)
{
low = mid + 1; // Search in the right half
}
else
{
high = mid - 1; // Search in the left half
}
}

// If the loop completes without finding the key


printf("Key %d not found in the array.\n", key);

return 0;
}

You might also like