Serene landscape depicting a path forking in two directions surrounded by a lush forest, symbolizing unordered and ordered linear search, with numerical values integrated into the environment and a signpost indicating 'Unordered' and 'Ordered' paths under a sky transitioning from dawn to dusk.

The linear search algorithm is probably the easiest algorithm you will encounter. There are two different forms of this algorithm, unordered and ordered linear search. The code does not change as the unordered and ordered are related to the data structure you loop through. It is fast to code and can work on any amount of data; however, this is an inefficient algorithm for larger amounts of data. This algorithm should be used on data with less than 100,000 entries regardless how fast computers are today. There are many different algorithms that can sort and search through data at a much faster rate. The linear search algorithm uses what is called a for-loop to search through data.

Linear Search

It is good practice to place the algorithm in its own function as you can reuse it in different scenarios. I am going to write this out in pseudo-code but you can find videos of the algorithm written in Java, Python, Node, and C down below. 

function linearSearch(data[10], target) {  
    for i = 0; i  data.length; i {
        if data[i] == target{       
            return i     
        }  
    } 
    return -1
}

Linear Search necessitates two parameters: data and target. Firstly, you may choose any data structure for data. Specifically in the demonstrations above, I utilize an array. Correspondingly, the target variable matches the item you are seeking. For instance, if you have an array of integers, the target would also be an integer. Consequently, we cycle through the data to see if any value at index i matches the target. When we find the target, we promptly return its index. Conversely, if we don’t find the target, we return -1 to signify that the search was unsuccessful. Essentially, writing the linear search algorithm is straightforward. However, its slow performance with large data sets primarily stems from the for-loop.

Particularly, in unordered data structures, the for-loop starts at 0 and continues until it reaches the size of the data. For instance, if the data contains 100 integers, the loop runs from 0 to 99, as arrays begin with 0. The size of the data can vary, which means the runtime of the unordered linear search algorithm is O(N). Conversely, with ordered data, achieving a best case of O(1) is possible if the desired item is at the index of 0 or N. Subsequently, checking these indexes before entering the loop may yield a constant runtime. Ultimately, you’ll find implementations of the unordered linear search algorithm in the provided coding examples.

For me algorithm discussions, head over to jstroup.dev for more!

Leave a Reply