This example describes the JS binary insert sorting algorithm. Share to everyone for your reference, specific as follows:
function Pusharraywithindex (arr, index, value) {//Add elements to the specified location of the array var Temarr = arr.slice (0, index);
Temarr.push (value);
Return Temarr.concat (Arr.slice (index));
}/* Test for pusharraywithindex var arr = [1, 2, 3, 4, 5];
arr = Pusharraywithindex (arr, 1, 9); Console.log (arr); */function Sortinsert (arr) {//insert sort var temarr = [];//temporary array, store sorted item function Getsorttmpindex (Subarr
, num) {var len = subarr.length; if (0 = len) return 0; When the array is empty, returns the start position var cpmindex = Math.ceil (LEN/2);
Calculates the position of the intermediate element if (Cpmindex > len-1) cpmindex = len-1;
if (num = = Subarr[cpmindex]) {//equal to return directly to Cpmindex;
} if (num > Subarr[cpmindex]) {//backward binary find cpmindex++;
return Cpmindex + getsorttmpindex (Subarr.slice (cpmindex), num);
} if (num < Subarr[cpmindex]) {//forward binary lookup return Getsorttmpindex (subarr.slice (0, Cpmindex), num);
(var i in arr) {var index = Getsorttmpindex (Temarr, arr[i]);//Find Arr[i's position in Temarr Console.log (' Index: ', index, ' num: ', arr[i], ' arr: ', Temarr); Temarr = Pusharraywithindex (Temarr, Index, arr[i]);
Inserts an element into the lookup location} return Temarr;
} var arr = [3, 7, 6, 5, 9, 1, 2, 3, 1, 7, 4];
Console.log (arr);
arr = Sortinsert (arr);
Console.log (arr);
I hope this article will help you with your JavaScript programming.