Unordered Linear Search

Let us assume that given an array, the order of the elements is unknown. this means The elements of the array are not sorted,So it is also called Unsorted Linear Search, In this situation, to search for elements, we need to scan complete array, and then see whether the required element is in the given list or not.

This image has an empty alt attribute; its file name is worst.png
This image has an empty alt attribute; its file name is worst.png

in above figures array is Unordered , There are three cases for finding an target element we need to search from starting index to required elements index.
Code of the Unordered Searching is :

    #include <stdio.h>
    int UnorderedSearching(int List[],int Target,int ListSize)
    {
        for(int i=0;i<ListSize;i++)
        {
            if(List[i]==Target)
                return i;
        }
        return -1;    // When Target is not available in the List.
    }
    int main()
    {
        int A[]={100,60,20,40,50,80};
        int ListSize = sizeof(A) / sizeof(A[0]);
        int Target=60;
        int indexVal=UnorderedSearching(A,Target,ListSize);
        if(indexVal==-1)
        {
             printf("Element is not in the List");
        }
        else
        {
            printf("Index of Target is %d :",indexVal);
        }
        return 0;
    }

Time Complexity

In Worst Case ,we need to traverse/scan whole list of array or list,if length of ListSize is n,then Time Complexity will be O(n).
In Best Case , if i got the required/target element in first attempt means if target element is present at index 0, then Time Complexity will be O(1).
In Average Case , if the target element is not at index 0 and also not at last index, then we have to find out the all the algorithmic complexities and take average of all,then Time Complexity will be O(n/2)=O(n).

Space Complexity

See the Fig-A , we used only one extra variable i for loop, So Space Complexity will be O(1).

Leave a Reply

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