Binary Search Algorithm C Implementation, Study notes of Data Structures and Algorithms

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

2017/2018

Uploaded on 09/30/2018

rohit-moon
rohit-moon 🇮🇳

1 document

1 / 1

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
#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();
}

Partial preview of the text

Download Binary Search Algorithm C Implementation and more Study notes Data Structures and Algorithms in PDF only on Docsity!

#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(); }