Friday, 5 October 2018

Linear Search

  Problem Statement :  write a C program with function to search a given element say key in arr[].

Logic:

Input : arr[]={10,20,30,40,25,35,45,55,60,65}
key=25
Output: 5
Element is found at 5 position

Input : arr[]={10,20,30,40,25,35,45,55,60,65}
key=26
Output: -1

Element not  found

Time complexity -  O(n)

A simple Algorithm for  linear search
1.  Start from the lower element of arr[] i.e arr[0] and one by one compare key with each element of arr[] till end of array.
2.  If key matches with an element, return the index.
3.  If key doesn’t match with any of elements, return -1
C Code for Linear Search using function:

#include<stdio.h>
int search(int arr[], int n, int key) ;//Function Prototype
int main()
{
int i,n,key,arr[10]; // declaration part
printf("\n Enter size of array:");
scanf("%d",&n);
printf("\n Enter element of array:");
for(i=0;i<n;i++)   // Scan array of size n
{
    scanf("%d",&arr[i]);
   
}
printf("\n Entered array is:");
for(i=0;i<n;i++)   // Print array
{
    printf("\"%d\"\t",arr[i]);
   
}
printf("\n Enter key to find in aray:");
scanf("%d",&key);   //scan key for finding
i=search(arr,n,key); //call  search function and assign return value to i
if(i==-1)    //now check return value if -1 then no element found
printf("\n Key not found in array");
else        //else show element position in array
printf("\n Key found in array at position %d",i);
return 0;
getchar();

}
int search(int arr[], int n, int key) //search function
{
    int i;
    for (i = 0; i < n; i++)  //check for key matching linearly one by one element
        if (arr[i] == key)  // Condition for cheching equity of key and array element
         return i+1;
    return -1;
}

/*
Output
Enter size of array:10
Enter element of array:10 20 30 40 50 60 70 80 90 100
Entered array is:"10" "20" "30" "40" "50" "60" "70" "80" "90" "100"
Enter key to find in array:80
Enter Key found in array at position 8

*/



No comments:

Post a Comment