
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Implementing insertion sort to sort array of numbers in increasing order using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.
Our function should make use of the insertion sort algorithm to sort this array of numbers in increasing order.
For example, if the input to the function is
Input
const arr = [5, 8, 1, 3, 9, 4, 2, 7, 6];
Output
const output = [1, 2, 3, 4, 5, 6, 7, 8, 9];
Example
Following is the code −
const arr = [5, 8, 1, 3, 9, 4, 2, 7, 6]; const insertionSort = (arr = []) => { let n = arr.length; for (let i = 1; i < n; i++) { let curr = arr[i]; let j = i-1; while ((j > -1) && (curr < arr[j])) { arr[j+1] = arr[j]; j--; } arr[j+1] = curr; }; return arr; } console.log(insertionSort(arr));
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- Related Articles
- Golang Program To Sort An Array In Ascending Order Using Insertion Sort
- Golang Program to sort an array in descending order using insertion sort
- Implementing Heap Sort using vanilla JavaScript
- JavaScript Program to Count rotations required to sort given array in non-increasing order
- Implementing Priority Sort in JavaScript
- Implementing counting sort in JavaScript
- How to implement insertion sort in JavaScript?
- Program to find out the number of shifts required to sort an array using insertion sort in python
- Use array as sort order in JavaScript
- Insertion sort using C++ STL
- Insertion Sort
- C program to sort a given list of numbers in ascending order using Bubble sort
- Using merge sort to recursive sort an array JavaScript
- Insertion Sort in C#
- Insertion sort in Java.

Advertisements