Linear Search

Linear search is a very simple search algorithm. In this type of search, a sequential search is done for all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection. The worst case time complexity of linear search is O(n) and the worst case space complexity is O(1).

Linear Search Algorithm

Linear Search ( Array A, Value x)

  1. Set i to 1
  2. if i > n then go to step 7
  3. if A[i] = x then go to step 6
  4. Set i to i + 1
  5. Go to Step 2
  6. Print Element x Found at index i and go to step 8
  7. Print element not found
  8. Exit

Pseudocode

procedure linear_search (list, value)

   for each item in the list
      if match item == value
         return the item's location
      end if
   end for

end procedure

C Program for Linear Search Algorithm

Code

#include< stdio.h>

void printArray(int[],int);

int main(void)
{
    int my_array[] = {0,21,22,50,55,99,100,120,180,200};
    int num,i;
    int array_size = sizeof(my_array)/sizeof(my_array[0]);
	
    printf("Array: ");
    printArray(my_array,array_size);
    
    printf("Enter a number to find its position in the given array: ");
    scanf("%d",&num);
    
    for(i=0;i <  array_size;i++)
    {
        if(my_array[i] == num)
        {
            printf("%d is present in the array at position %d.\n",num,i+1);
            break;
        }
    }
    if(i >= array_size)
        printf("%d is not present in the array.\n",num);

    return 0;
}

void printArray(int arr[],int get_size)
{
    int i;
	
    for(i=0;i < get_size;i++)
        printf("%d ",arr[i]);
    printf("\n");
}

Output

Array: 0 21 22 50 55 99 100 120 180 200
Enter a number to find its position in the given array: 99
99 is present in the array at position 6.

Trending

C Programming

Remember to follow community guidelines and don't go off topic.