× back Linear Search Binary Search
Next Topic → ← Previous Topic

Searching

Linear Search

Basic procedure ↓

                
for(i = 0; i < length; i++)
{
    if(key == A[i])
        return i;
}
return -1;
                
            

Time complexity of Linear Search

                   
#include <stdio.h>
int linearSearch(int arr[], int key)
{
    int i;
    int size = 10;
    for (i = 0; i < size; i++)
    {
        if (key == arr[i])
            return i;
    }
    return -1;
}
int main()
{
    int arr[10] = {3, 2, 4, 5, 6, 7, 8, 9, 11, 23};
    printf("The element is present at index %d", linearSearch(arr, 6));
    return 0;
}
                   
               

Binary Search

                
Algorithm BinSearch(l, h, key)
{
    while(l <= h)
    {
        mid = (l + h) / 2;
        if(key == A[mid])
            return mid;
        else if(key < A[mid])
            h = mid - 1;
        else 
            l = mid + 1;
    }
    return -1;
}
                
            

Code ↓

                   
#include <stdio.h>
#define MAX 10
int arr[MAX] = {12, 24, 25, 36, 45, 46, 47, 48, 59, 63};
int BinarySearch(int key)
{
    int l, mid, h;
    l = 0;
    h = MAX - 1;
    while (l <= h)
    {
        mid = (l + h) / 2;
        if (key == arr[mid])
            return mid;
        else if (key < arr[mid])
            h = mid - 1;
        else
            l = mid + 1;
    }
    return -1;
}
int main()
{
    printf("Value is present at index %d\n", BinarySearch(36));
    return 0;
}