Insertion sort is considered to be one of the building blocks of sorting. It has its place in real-world use cases while not being too hard to understand.
So how does it work? Well, we basically loop over every element and insert the value at the position of the last previous that meets our condition.
So, let's take a look at a step-by-step explanation.
Now let's take a look at what our insertionSort function should look like:
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const current = arr[i];
for (var j = i - 1; j >= 0 && arr[j] > current; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = current;
}
return arr;
}
// Example:
// Initial array: [4, 3, 2]
// After first iteration: [3, 4, 2]
// After second iteration: [2, 3, 4]
Let's step through this code together:
Note: j + 1 is necesarry because j will always be -1 where our current value should go as our loop keeps decrementing its value until our condition is met (j >= 0 && arrj > current) so it could be -1 if our current value should be inserted at the zero index.
This algorithm involves a loop inside a loop, meaning a quadratic time complexity (Big O of n²), definitely not the best performance-wise, but as we mentioned, we always have a subarray sorted, which could be helpful if we received values gradually like from a stream.
Here are some key points to consider:
Insertion sort can be particularly useful in scenarios where the data is nearly sorted or when dealing with small datasets. It is also beneficial in situations where you receive values gradually, such as from a stream, because it can efficiently insert new elements into an already sorted sequence.
Additionally, insertion sort is often used as a part of more complex algorithms, such as Timsort, which is used in Python's sorting algorithm and Java's Arrays.sort() for non-primitive types. This hybrid sorting algorithm takes advantage of insertion sort's efficiency on small or nearly sorted datasets.
Let's consider a more realistic example where we have an array of objects, and we want to sort these objects based on a specific key. We can modify the insertionSort function to accept a second parameter, key, which specifies the property to sort by.
Here's how you can do it:
function insertionSort(arr, key) {
for (let i = 1; i < arr.length; i++) {
const current = arr[i];
let j = i - 1;
while (j >= 0 && arr[j][key] > current[key]) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
return arr;
}
// Example usage:
const data = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
insertionSort(data, 'age');
// [
// { name: 'Bob', age: 25 },
// { name: 'Alice', age: 30 },
// { name: 'Charlie', age: 35 }
// ]
In this example, the insertionSort function sorts the array of objects based on the age property. The key parameter allows you to specify any property of the objects to sort by, making the function more flexible and reusable.
Insertion sort is a fundamental sorting algorithm that is easy to understand and implement. While it may not be the most efficient for large datasets due to its quadratic time complexity, it shines in scenarios where the data is nearly sorted or when dealing with small datasets. Its ability to sort data incrementally makes it particularly useful for streaming data or as a component in more complex sorting algorithms.
Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.
Feel free to me through this learning journey by providing any feedback and if you wanna support me: