Skip to content

🔭Linear Search : still searching who stole my assignments & notes(👀-bombastic side eye)

Notifications You must be signed in to change notification settings

Abhishek-Singh296/Linear-Search

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

Linear-Search

Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set.


Working

The following steps are followed to search for an element k = 1 in the list below.

image

1.Start from the first element, compare k with each element x.

image

2.If x == k, return the index.

image

3.Else, return not found.


Algorithm

Step 1: First, read the search element (Target element) in the array. Step 2: Set an integer i = 0 and repeat steps 3 to 4 till i reaches the end of the array. Step 3: Match the key with arr[i]. Step 4: If the key matches, return the index. Otherwise, increment i by 1.

Code

#include <stdio.h>
 
int search(int arr[], int N, int x)
{
    int i;
    for (i = 0; i < N; i++)
        if (arr[i] == x)
            return i;
    return -1;
}
 
// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    int result = search(arr, N, x);
    (result == -1)
        ? printf("Element is not present in array")
        : printf("Element is present at index %d", result);
    return 0;
}

Output

Screenshot 2023-04-26 090458


About

🔭Linear Search : still searching who stole my assignments & notes(👀-bombastic side eye)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages