Ads by ProfitSence
Close

Insertion sort javascript

Last Updated on Sunday 9th Oct 2022

Insertion sort javascript.

  • Insertion Sort is one of the simpler sorting algorithms. It's highly intuitive, stable, in-place, and of comparison-type.
  • Despite it being less efficient than algorithms such as Merge Sort and Quick Sort, it is able to outperform them in certain use cases.
			
					['Charles', 'Bianca', 'Alex', 'Brandon']

// Alphabetical order by first letter, the output would be

['Alex', 'Bianca', 'Brandon', 'Charles']

			
	

insertion sort javascript example

Insertion Sort works by comparing an element with the elements to its left, until it reaches an element that is smaller than it; the element is then inserted in front of the smaller element.

			
					function insertionSort(arr) {
    for (let i = 1; i < arr.length; i++) {
        let currentValue = arr[i];
        let j = i - 1;
        while ((j > -1) && (currentValue < arr[j])) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = currentValue;
    }
    return arr;
}

			
	

Ausgabe

			
					console.log(insertionSort([12, 31, 13, 57, 15]))
// [ 12, 13, 15, 31, 57 ]

			
	
			
					const insertionSort = (array) => {
  for (outer = 1; outer < array.length; outer++) {
    for (inner = 0; inner < outer; inner++) {
      console.log(array.join(' '))
      if (array[outer] < array[inner]) {
        const [element] = array.splice(outer, 1)
        array.splice(inner, 0, element)
      }
    }
  }
  console.log(array.join(' '))
  return array
}

console.log(insertionSort([5, 3, 4, 1, 2]))

			
	
			
					5 3 4 1 2
3 5 4 1 2
3 5 4 1 2
3 4 5 1 2
1 3 4 5 2
1 3 4 5 2
1 3 4 5 2
1 3 4 5 2
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

			
	
  • For small arrays, Insertion Sort would be just fine.Sorting data in real-time
  • Sorting the large and randomly distributed arrays then what algorithm we use begins to matter.
  • It Means larger arrays that aren’t almost sorted.