UNPKG

javascript-algorithms-and-data-structures

Version:

Algorithms and data-structures implemented on JavaScript

36 lines (28 loc) 978 B
import Sort from '../Sort'; export default class InsertionSort extends Sort { sort(originalArray) { const array = [...originalArray]; // Go through all array elements... for (let i = 0; i < array.length; i += 1) { let currentIndex = i; // Call visiting callback. this.callbacks.visitingCallback(array[i]); // Go and check if previous elements and greater then current one. // If this is the case then swap that elements. while ( array[currentIndex - 1] && this.comparator.lessThan(array[currentIndex], array[currentIndex - 1]) ) { // Call visiting callback. this.callbacks.visitingCallback(array[currentIndex - 1]); // Swap the elements. const tmp = array[currentIndex - 1]; array[currentIndex - 1] = array[currentIndex]; array[currentIndex] = tmp; // Shift current index left. currentIndex -= 1; } } return array; } }