Thursday, 21 February 2019

Linear Search in C without using function

In Searching, you are given a set of elements and a key, you have to find the location of given key in that set.
These algorithms are generally classified into two categories:
  1. Sequential Search: In this, the set of elements is traversed sequentially and every element is checked against key. For example: Linear Search.
  2. Interval Search: These algorithms are used when elements in the given set are sorted. These algorithms are more efficient than Linear Search.For Example: Binary Search.
(1).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.
 
  Problem: Given an array array[] of size n, write a program in C to search a given element x in array[].
   Examples :
     Input : array[] = { 10, 15, 9, 12, 50,32 };
     key = 15;
     Output : 2
     Element key is present at index 2.
   
     Input : array[] = { 10, 15, 9, 12, 50,32 };
     key = 65;
     Output : -1
     Element key does not exist in given set of elements.
  
Solution:
#include <stdio.h>
     int main()
      {
       int array[] = { 10, 15, 9, 12, 50,32 };
       int key = 9,arraySize=0,i,index=-1;
      
     //finding the size(no of elements) of array
       arraySize = sizeof(array)/ sizeof(int);
      
       for (i = 0; i < arraySize; i++){             
         if (array[i] == key){
            index=i;  //key found at index i
         }          
       }
      
       if(index!=-1)
         printf("Element %d found at position %d.\n",key,index+1);
       else
         printf("Element %d not exist in given set of elements.\n",key);
              
       return 0;
      }    

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

No comments:

Post a Comment