JS semi-insertion Sorting Algorithm instance_javascript skills

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.