
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The implementation of a binary search algorithm in c language. The user is asked to enter the number of elements in an array and the elements themselves. After that, the user is asked to enter a value to search for in the array. The binary search algorithm is then applied to find the location of the value in the array.
Typology: Study notes
1 / 1
This page cannot be seen from the preview
Don't miss anything!

#include <stdio.h> #include <conio.h> void main() { int c, first, last, middle, n, search, array[100]; clrscr(); printf("Enter number of elements\n"); scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) scanf("%d",&array[c]);
printf("Enter value to find\n"); scanf("%d", &search);
first = 0; last = n - 1; middle = (first+last)/2;
while (first <= last) { if (array[middle] < search) first = middle + 1; else if (array[middle] == search) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1;
middle = (first + last)/2; } if (first > last) printf("Not found! %d isn't present in the list.\n", search);
getch(); }