Posted on by Kalkicode
Code Sorting

Insertion sort on array in node js

Js program for Insertion sort on array. Here mentioned other language solution.

//  Node js program for
//  Insertion sort on array

// Swap the given index value in array
function swap(arr, first, second)
{
	// Swap element value by index
	var temp = arr[first];
	arr[first] = arr[second];
	arr[second] = temp;
}
// Performing insertion sort by given array and its size
function sort(arr, n)
{
	// Outer loop
	for (var i = 0; i < n - 1; ++i)
	{
		// Inner loop handle the insertion sort operation
		for (var j = i + 1; j > 0 && arr[j - 1] > arr[j]; j--)
		{
			// Swap array element
			swap(arr, j, j - 1);
		}
	}
}

function main()
{
	// Define array elements
	var arr = [5, 1, 0, 9, 3, 1, 6, -3, 7, 1, -5, 12];
	// Get the size of array
	var n = arr.length;
	console.log("Before Sort : ", arr);
	// Run insertion sort 
	sort(arr, n);
	console.log("After Sort  : ", arr);
}
// Start program execution
main();

Output

Before Sort :  [ 5, 1, 0, 9, 3, 1, 6, -3, 7, 1, -5, 12 ]
After Sort  :  [ -5, -3, 0, 1, 1, 1, 3, 5, 6, 7, 9, 12 ]

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment