0
0
DSA Javascriptprogramming~30 mins

Insertion Sort Algorithm in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Insertion Sort Algorithm
📖 Scenario: You have a list of numbers that you want to arrange in order from smallest to largest, just like organizing books by height on a shelf.
🎯 Goal: Build a program that sorts a list of numbers using the insertion sort method, which places each number in its correct spot one by one.
📋 What You'll Learn
Create an array called numbers with the exact values [8, 3, 5, 4, 6].
Create a variable called n that stores the length of the numbers array.
Use a for loop with the variable i starting from 1 up to n to iterate through the array.
Inside the loop, create a variable called key to hold the current number at index i.
Use a while loop with variable j to move elements greater than key one position ahead.
Place the key in its correct sorted position.
Print the sorted numbers array.
💡 Why This Matters
🌍 Real World
Sorting is used everywhere, like arranging books, organizing files, or displaying search results in order.
💼 Career
Understanding sorting algorithms helps in software development, data analysis, and optimizing performance in many tech jobs.
Progress0 / 4 steps
1
Create the initial array
Create an array called numbers with these exact values: [8, 3, 5, 4, 6].
DSA Javascript
Hint

Use const numbers = [8, 3, 5, 4, 6]; to create the array.

2
Set up the length variable
Create a variable called n that stores the length of the numbers array.
DSA Javascript
Hint

Use const n = numbers.length; to get the array length.

3
Implement the insertion sort logic
Use a for loop with variable i from 1 to n. Inside it, create a variable key to hold numbers[i]. Use a while loop with variable j to move elements greater than key one position ahead. Finally, place key in its correct position.
DSA Javascript
Hint

Use a for loop starting at 1, a while loop to shift larger numbers, and place the key correctly.

4
Print the sorted array
Write a console.log statement to print the sorted numbers array.
DSA Javascript
Hint

Use console.log(numbers); to show the sorted array.