This article mainly introduces the JS semi-insertion sorting algorithm, and analyzes in detail the related skills of JavaScript to achieve semi-insertion sorting in the form of a complete example, which has some reference value, for more information about JS semi-insertion sorting algorithms, see the examples in this article. We will share this with you for your reference. The details are as follows:
Function pushArrayWithIndex (arr, index, value) {// Add the element to the specified position of the array var temArr = arr. slice (0, index); temArr. push (value); return temArr. concat (arr. slice (index);}/* test for pushArrayWithIndexvar arr = [1, 2, 3, 4, 5]; arr = pushArrayWithIndex (arr, 1, 9); console. log (arr); */function sortInsert (arr) {// Insert the sorted var temArr = []; // temporary array, storing the sorted item function getSortTmpIndex (subArr, num) {var len = subArr. length; if (0 = len) return 0; // if the array is empty, return the first position var cpmIndex = Math. ceil (len/2); // calculate the location of the intermediate element if (cpmIndex> len-1) cpmIndex = len-1; if (num = subArr [cpmIndex]) {// return the return cpmIndex;} if (num> subArr [cpmIndex]) {// returns cpmIndex + getSortTmpIndex (subArr. slice (cpmIndex), num);} if (num <subArr [cpmIndex]) {// returns getSortTmpIndex (subArr. slice (0, cpmIndex), num) ;}for (var I in arr) {var index = getSortTmpIndex (temArr, arr [I]); // find the location of arr [I] In temArr console. log ('index: ', index, 'num:', arr [I], 'Arr: ', temArr); temArr = pushArrayWithIndex (temArr, index, arr [I]); // Insert the element to the search 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 design JavaScript programs.