This C program compares two searching algorithms – Binary and Sequential Search.

Sequential search is used to find a key in a randomly arranged array. Searching time is O(n). Binary search on the other hand is implemented in a sorted array and is much faster than linear search. Its time complexity is O(log(n)).

Here is the source code of the C program to compare binary and sequential searching algorithms. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

`#include <stdio.h>`

`#define MAX 10`

int linearsearch(int numbers[], int key)

`{`

int i;

for (i = 0; i < MAX; i++)

`{`

if (key == numbers[i])

return i;

`}`

return -1;

`}`

int binarysearch(int numbers[], int key)

`{`

int l = 0, u = MAX - 1;

int c, mid;

while (l <= u){

mid = (l + u) / 2;

if (key == numbers[mid]){

return mid;

`}`

else if (key < numbers[mid]){

u = mid - 1;

`}`

`else`

l = mid + 1;

`}`

return -1;

`}`

int main() {

int numbers[MAX];

int i;

int index, key;

printf("Enter %d numbers : ", MAX);

for (i = 0; i < MAX; i++)

`{`

scanf("%d", &numbers[i]);

`}`

printf("\nEnter a key to find using linear search: ");

scanf("%d", &key);

index = linearsearch(numbers, key);

if ( index >= 0)

printf("\n%d found at index %d using linear search.", key, index);

`else`

printf("\nNot found!!");

printf("\nEnter %d numbers in increasing order: ", MAX);

for (i = 0 ; i < MAX; i++)

scanf("%d", &numbers[i]);

printf("\nEnter a key to find using binary search: ");

scanf("%d", &key);

index = binarysearch(numbers, key);

if (index >= 0 )

printf("Found at index %d", index);

`else`

printf("\nNot found!!!");

return 0;

`}`

$ gcc comparesearch.c -o comparesearch $ ./comparesearch Enter 10 numbers : 1 21 45 66 98 85 78 4 55 48 Enter a key to find using linear search: 45 45 found at index 2 using linear search. Enter 10 numbers in increasing order: 13 21 45 66 98 99 112 155 185 202 Enter a key to find using binary search: 66 Found at index 3

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.