JavaScript Program to Implement Insertion Sort

JavaScript Program to Implement Insertion Sort

Insertion Sort is a simple and friendly sorting algorithm that feels very natural to understand. It works the same way people often sort playing cards in their hands. You pick one card at a time and place it in the correct position among the already sorted cards. In JavaScript, Insertion Sort follows this same idea by taking one element and inserting it into its proper place in a sorted part of the array.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

This algorithm matters because it teaches beginners how sorting can be done step by step with clear logic. Insertion Sort is often used when working with small data sets or when the array is already mostly sorted. It may not be the fastest sorting method, but it is excellent for learning and building confidence with JavaScript programs and algorithms.

Program 1: Insertion Sort using basic loops

This program shows the most common way to implement Insertion Sort in JavaScript using loops. It is easy to read and perfect for beginners who are learning how arrays work.

let numbers = [12, 11, 13, 5, 6];

for (let i = 1; i < numbers.length; i++) {

    let key = numbers[i];
    let j = i - 1;

    while (j >= 0 && numbers[j] > key) {

        numbers[j + 1] = numbers[j];
        j = j - 1;

    }

    numbers[j + 1] = key;

}

console.log("Sorted array:", numbers);

This program starts from the second element and compares it with the elements before it. If the element is smaller, it moves left until it reaches the correct position. Beginners find this useful because it clearly shows how values shift and settle into place, making the sorting process easy to follow.

Program 2: Insertion Sort with clear step-by-step logic

This version focuses on clarity by separating the key value and comparison process. It helps beginners understand what is happening at each step.

let values = [9, 3, 1, 5, 4];

for (let i = 1; i < values.length; i++) {

    let current = values[i];
    let position = i;

    while (position > 0 && values[position - 1] > current) {

        values[position] = values[position - 1];
        position--;

    }

    values[position] = current;

}

console.log("Sorted array:", values);

Here, the program stores the current value and shifts larger elements to the right. Once the correct spot is found, the value is inserted. This approach is helpful because it mirrors how people naturally sort items and makes the logic feel simple and intuitive.

Program 3: Insertion Sort using recursion

This program uses recursion instead of loops to perform Insertion Sort. It is useful for learners who want to understand how sorting works with function calls.

let data = [8, 4, 3, 7, 6];

function insertionSortRecursive(arr, n) {

    if (n <= 1) {
        return;
    }

    insertionSortRecursive(arr, n - 1);

    let last = arr[n - 1];
    let j = n - 2;

    while (j >= 0 && arr[j] > last) {

        arr[j + 1] = arr[j];
        j--;

    }

    arr[j + 1] = last;

}

insertionSortRecursive(data, data.length);
console.log("Sorted array:", data);

This recursive version sorts the array one element at a time by calling itself on smaller portions. Each call places the last element in the correct position. Beginners can use this program to learn recursion while still working with a familiar and easy algorithm.

Program 4: Insertion Sort in descending order

This example sorts the array from largest to smallest instead of the usual smallest to largest. It shows how flexible Insertion Sort can be.

let scores = [15, 10, 20, 8, 25];

for (let i = 1; i < scores.length; i++) {

    let key = scores[i];
    let j = i - 1;

    while (j >= 0 && scores[j] < key) {

        scores[j + 1] = scores[j];
        j--;

    }

    scores[j + 1] = key;

}

console.log("Sorted array (descending):", scores);

In this program, the comparison sign is reversed so larger values move forward. This helps beginners see how small changes in conditions can change the sorting order. It is a great way to experiment and understand comparisons better.

Program 5: Insertion Sort using a reusable function

This version wraps the Insertion Sort logic inside a function so it can be reused with different arrays. It feels closer to real-world JavaScript usage.

function insertionSort(arr) {

    for (let i = 1; i < arr.length; i++) {

        let key = arr[i];
        let j = i - 1;

        while (j >= 0 && arr[j] > key) {

            arr[j + 1] = arr[j];
            j--;

        }

        arr[j + 1] = key;

    }

    return arr;

}

let items = [7, 2, 9, 1, 5];

console.log("Sorted array:", insertionSort(items));

This program makes the code clean and reusable. Beginners can easily pass different arrays to the function and see how it works. It also helps learners understand how algorithms are commonly written in JavaScript projects.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Insertion Sort in JavaScript in a simple and friendly way.

Q1. What is Insertion Sort in JavaScript?
Insertion Sort is a simple sorting algorithm that builds the sorted array one element at a time. It places each value in its correct position using comparisons.

Q2. Is Insertion Sort faster than Bubble Sort?
Insertion Sort is usually faster than Bubble Sort for small or nearly sorted arrays. Both are mainly used for learning rather than performance.

Q3. Where is Insertion Sort used?
Insertion Sort is often used when dealing with small data sets or when data is almost sorted. It is also popular in teaching and interviews.

Q4. Can Insertion Sort work with strings?
Yes, Insertion Sort can sort strings as long as proper comparisons are used. JavaScript supports string comparison, making this possible.

Q5. Should beginners learn Insertion Sort?
Yes, Insertion Sort is excellent for beginners. It teaches careful comparison, shifting values, and logical thinking.

Conclusion

Insertion Sort is a gentle and powerful way to learn sorting in JavaScript. It shows how values move, how comparisons work, and how order is built step by step. By exploring different versions like loops, recursion, descending order, and reusable functions, beginners can gain a strong understanding of the algorithm.

The best way to learn Insertion Sort is by practicing it with different data. Try changing numbers, sorting words, or writing your own version. With regular practice, you will feel more confident and ready to explore more advanced sorting algorithms in JavaScript.

Scroll to Top