Search algorithm: Front and back (unsorted)

Luis Aguilar
2 min readAug 3, 2019

--

Introduction

This time we’ll implement an algorithm to search an element in an unsorted array. The most common algorithm to search an element in an unsorted array is using a linear search, checking element by element from the beginning to the end, this algorithm takes O(n) complexity. Using the front and back algorithm can take us a half of time.

Time Complexity: O(n)

Space complexity: O(1)

How it works

The way of this algorithm works is similar to a linear search, but the difference is that uses two indexes to search, the first one starts to the beginning (position 0) and the second one starts to the end (position length -1).

The first index starts from the position 0 to up and the second one starts from the last position to down, when the first index is greater then the second one the iterations stop or when the value is found.

Implementation

Now, we’ll implement the algorithm in python:

Front and back algorithm

This is an easy algorithm to implement and useful. Now you can perform searches a little faster.

--

--

Luis Aguilar

Algorithms, Angular, Typescript, JavaScript, Rust 💻 | Site: https://insomniocode.com | GitHub: https://github.com/Lugriz 🐈🐙 | youtube: Insomniocode 🎬