JavaScript

Insertion Sort in JavaScript

We can create a script in Javascript to sort the elements of an array using insertion sort. The insertion sort algorithm is only useful for small items because it takes more time to sort a large number of items. Here’s how the process works:
 

Example:


Source: Wikipedia.org

 
 

Script to sort an array using the insertion sort algorithm
function sort(arr) {
	//number of elements in the array
	var len = arr.length;     	
	var tmp, i, j;                  
	
	for(i = 1; i < len; i++) {
		//store the current value
		tmp = arr[i]
		j = i - 1
		while (j >= 0 && arr[j] > tmp) {
			// move the number
			arr[j+1] = arr[j]
			j--
		}
		//Inserts the temporary value at the correct position
		arr[j+1] = tmp
	}
	return arr
}

var arr = [5, 8, 11, 6, 1, 9, 3];
sort(arr);
console.log(arr);

Output:

[1, 3, 5, 6, 8, 9, 11]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *