JS binary Insert Sort algorithm Example _javascript skill

Source: Internet
Author: User

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.

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.