Javascript Algorithm Array Sort Insertion Sort 2
var arr = [5, 2, 4, 6, 1, 3]; console.log(arr);// ww w . j ava 2 s .co m console.log(insertion_sort(arr)); function insertion_sort(array) { for(var i = 1; i < array.length; i++) { var key = array[i]; var j = i - 1; while(j >= 0 && array[j] > key) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } return array; }
sort an array of numbers by inserting from an unsorted partition to a sorted partition
function insertionSort(arr, comparator) { if (!comparator) { comparator = (a, b) => a < b;/*from w w w . java 2 s . c o m*/ } let current; for (let i = 1; i < arr.length; i++) { current = i; while(current > 0 && comparator(arr[current], arr[current-1])) { swap(current, current-1, arr); current--; } } return arr; } function swap(i, j, arr) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } let nums = [5, 4, 3, 2, 1, 6, 8, 9, 7]; insertionSort(nums, (a, b) => a > b); console.log(nums);