Sequential Search using C

Last Updated on November 28th, 2020 at 01:28 pm

This example shows how Sequential Search algorithm works. In sequential or linear search an element is searched or found in a list.

Simple way to search for a key value k in an array a is to compare the values of the elements in a with k. The process starts with the first element of the array and k and comparison continues as long as either the comparison does not result in a success or the list of elements in the array are exhausted. This method of searching is known as sequential search or linear search.

Time Complexity

Worst Complexity: O(n)
Average Complexity: O(n)
Space Complexity: O(1)
Worst-case Space Complexity: O(1) iterative

Algorithm Implementation

The following code example will return the index of the array when a successful search is found for the given key value and when the search is unsuccessful, the function returns -1.

The complete source code given below in C programming language.

/* 
 * File:   SequentialSearch.c
 * Author: https://roytuts.com
 */

#include <stdio.h>
#include <stdlib.h>

int sequentialSearch(int k, int a[], int n) {
    int i = 0;
    while (i < n) {
        if (k == a[i]) {
            break;
        } else {
            i++;
        }
    }
    if (i < n) {
        return i;
    } else {
        return -1;
    }
}

int main() {
    int choice, value;
    int a[] = {1, 8, 6, 9, 4, 5, 6};
    printf("\n:: Sequential Search ::\n");
    while (1) {
        printf("\nChoose from below Menu\n");
        printf("1. Search\n2. Exit\n");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: printf("Enter the value to be searched: ");
                scanf("%d", &value);
                int index = sequentialSearch(value, a, 7);
                if (index > 0) {
                    printf("\nValue found at index %d in the array\n", index);
                } else {
                    printf("\nValue not found in the array\n");
                }
                break;
            case 2: exit(0);
            default: printf("\nWrong selection!!! Please try again!!!\n");
        }
    }
}

Testing the Program

Executing the above C program will give you the following output:

:: Sequential Search ::

Choose from below Menu
1. Search
2. Exit

Enter your choice: 1
Enter the value to be searched: 2

Value not found in the array

Choose from below Menu
1. Search
2. Exit

Enter your choice: 1
Enter the value to be searched: 5

Value found at index 5 in the array

Choose from below Menu
1. Search
2. Exit

Enter your choice: 2

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *