Thursday, 21 February 2019

Linear Search using function in C

Linear Search

  1. Traverse given array starting from first element.
  2. Compare element at current index with given key.
  3. If key matches with an element, return the index.
  4. If key doesn’t match with any of elements, return -1.
//C program for linear search using function
#include <stdio.h>
     int main(void)
      {
       int array[] = { 10, 15, 9, 12, 50,32 };
       int key = 90,arraySize=0,i,result;
       //function declaration
       int linearSearch(int array[],int n,int value);
      //finding the size(no of elements) of array
       arraySize = sizeof(array)/ sizeof(int);
       //function calling
       result=linearSearch(array,arraySize,key);
       if(result!=-1)
         printf("Element %d found at position %d.\n",key,result+1);
       else
         printf("Element %d does not exist.\n",key);
               return 0;
      }   
      //function definition
      int linearSearch(int array[],int n,int value){
      int index=-1,i;
       for (i = 0; i < n; i++){                 
         if (array[i] == value){
            index=i;  //key found at index i
            break;
         }          
       }
               return index;

      }



Please comment if you find anything incorrect, or you want to improve the topic discussed above. 

No comments:

Post a Comment