You are on page 1of 4

Linear Search:

This search method searches for an element by visiting all the elements sequentially until the element is
found or the array finishes. It follows the array traversal method.

Binary Search:
This search method searches for an element by breaking the search space into half each time it finds the
wrong element. This method is limited to a sorted array. The search continues towards either side of the
mid, based on whether the element to be searched is lesser or greater than the mid element of the current
search space.

Difference between linear search and binary search


Linear search:

Works on both sorted and unsorted arrays

Binary search:

Works only on sorted arrays

Linear search program:

#include<stdio.h>

int main()

int a[20],i,x,n;

printf("enter the limit of an array");

scanf("%d",&n);
for(i=0;i<n;i++)

printf("Enter array elements");

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

printf("Enter element to search:");

scanf("%d",&x);

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

if(a[i]==x)

break;

if(i<n)

printf("Element found at index %d",i);

else

printf("Element not found");

Output:

Enter the limit of an array4

Enter array elements12

Enter array elements42

Enter array elements34

Enter array elements45

Enter elements to search:42

Element found at index 1


Binary search program:

#include <stdio.h>

int main()

int i, low, high, mid, n, search, array[100];

printf("Enter the limit of an array");

scanf("%d",&n);

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

printf("Enter the elements");

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

printf("Enter value to search");

scanf("%d", &search);

low = 0;

high = n - 1;

mid = (low+high)/2;

while (low <= high) {

if(array[mid] < search)

low = mid + 1;

else if (array[mid] == search) {

printf("%d found at location %d", search, mid+1);

break;

else

high = mid - 1;
mid = (low + high)/2;

if(low > high)

printf("Not found! %d isn't present in the list.n", search);

Output:

Enter the limit of an array4

Enter the elements12

Enter the elements13

Enter the elements14

Enter the elements15

Enter value to search13

13found at location 2

You might also like