Javascript Array custom sort, and get sorted to save the original index of the same bit array (heap sort implementation)

Source: Internet
Author: User
Tags javascript array

For example , array a:

[

0:5,

1:2,

2:4,

3:3,

4:1

]

The results are as follows: [1, 2, 3, 4, 5], but sometimes there is a need to keep the pre-order position in a single array, as in the preceding example: [4, 1, 3, 2, 0], so a separate array ordering process is implemented using heap sorting.

The code is as follows:

functionArraykeys (arr) {vari = 0, Len=arr.length, Keys= [];  while(I <Len) {Keys.push (i++); }        returnkeys; }     
//Determine if the variable is an array functionIsArray (arr) {return({}). Tostring.call (arr). Match (/^\[[^\s]+\s* ([^\s]+) \]$/) [1] = = ' Array '; }
//Heap sort functionHeapsort (arr, keys, order) {if(!isarray (arr) | |!isarray (keys))return ; varOrder = (order + "). toLowerCase () = = ' desc '? Order: ' ASC '; //Swap Location functionchangepos (arr, cur, left) {vartmp; TMP=Arr[cur]; Arr[cur]=Arr[left]; Arr[left]=tmp; } //constructing a two-fork heap functionHeap (arr, start, end, Ismax) {varIsmax = Ismax = = undefined?true: Ismax,//is the maximum heap, no minimum heapCur = start,//the location of the current nodeleft = 2 * cur + 1;//the location of the left child for(; left <= end; cur = left, left = 2 * left + 1) { //left is the right child. if(Left < end && ((Ismax && Arr[left] < Arr[left + 1]) | | (!ismax && Arr[left] > arr[left + 1] )) {left++;//take larger/smaller in the left and right child nodes } if((Ismax && arr[cur] >= arr[left]) | | (!ismax && Arr[cur] <=Arr[left])) { Break; } Else { //The original index follows the sort synchronizationchangepos (keys, cur, left); Changepos (arr, cur, left); } } } return+function () { //from (n/2-1)-to-0 successive traversal. After the traversal, the resulting array is actually a two-fork heap for(varLen = arr.length, i = Math.floor (LEN/2)-1; I >= 0; i--) {heap (arr, I, Len-1, order = = ' ASC '); } //adjusts the sequence from the last element, shrinking the adjustment until the first element for(i = len-1; i > 0; i--) {Changepos (keys,0, i); Changepos (arr,0, i); //Adjust arr[0...i-1], so that arr[0...i-1] is still a maximum/small heap //That is, ensure that arr[i-1] is the maximum/small value in Arr[0...i-1]Heap (arr, 0, i-1, order = = ' ASC ')); } }(); }
//Test varAA = [5, 2, 8, 9, 1, 3, 4, 7, 6];varKK =Arraykeys (AA); heapsort (AA, KK, ' ASC ');console.log (AA); //after sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9] Console.log (KK); //Original index: [4, 1, 5, 6, 0, 8, 7, 2, 3]

Of course, this method can also be written to Array.prototype.heapSort under the premise of ensuring security, so that it can be called directly with the array, and the code is slightly modified, as follows:

Array.prototype._heapsort =function(keys, order) {vararr = This, Keys= ({}). Tostring.call (keys) = = ' [Object Array] '?keys: [], Order= (Order + "). toLowerCase () = = ' desc '? Order: ' ASC '; //Swap Location        functionchangepos (arr, cur, left) {vartmp; TMP=Arr[cur]; Arr[cur]=Arr[left]; Arr[left]=tmp; }        //constructing a two-fork heap        functionHeap (arr, start, end, Ismax) {varIsmax = Ismax = = undefined?true: Ismax,//is the maximum heap, no minimum heapCur = start,//the location of the current nodeleft = 2 * cur + 1;//the location of the left child             for(; left <= end; cur = left, left = 2 * left + 1) {                //left is the right child.                if(Left < end && ((Ismax && Arr[left] < Arr[left + 1]) | | (!ismax && Arr[left] > arr[left + 1] )) {left++;//take larger/smaller in the left and right child nodes                }                if((Ismax && arr[cur] >= arr[left]) | | (!ismax && Arr[cur] <=Arr[left])) {                     Break; } Else {                    //The original index follows the sort synchronizationchangepos (keys, cur, left);                Changepos (arr, cur, left); }            }        }        return+function () {            //from (n/2-1)-to-0 successive traversal. After the traversal, the resulting array is actually a two-fork heap             for(varLen = arr.length, i = Math.floor (LEN/2)-1; I >= 0; i--) {heap (arr, I, Len-1, order = = ' ASC '); }            //adjusts the sequence from the last element, shrinking the adjustment until the first element             for(i = len-1; i > 0; i--) {Changepos (keys,0, i); Changepos (arr,0, i); //Adjust arr[0...i-1], so that arr[0...i-1] is still a maximum/small heap                //That is, ensure that arr[i-1] is the maximum/small value in Arr[0...i-1]Heap (arr, 0, i-1, order = = ' ASC '));    }        }(); };

Javascript Array custom sort, and get sorted to save the original index of the same bit array (heap sort implementation)

Related Article

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.