The implementation and application of Array.Sort () in JavaScript __java

Source: Internet
Author: User
Tags array length
the implementation and application of Array.Sort () in JavaScript 1. The array.js of the V8 engine

The sort () method in JS is used to sort the array elements, and how they are implemented. Looking at the data found that the V8 engine sort function only gives two sorts of Insertionsort and QuickSort, the array length is less than or equal to 22 of the insertion sort insertionsort, compared to the 22 large array uses the Quick sort QuickSort. The source wrote:

In-place QuickSort algorithm.
For short (length <=) arrays, insertion the sort is used for efficiency.

Also, attach the sort implementations of the other engines

Mozilla/firefox: Merge sort (jsarray.c source)
Webkit: The bottom implementation of the C + + library in the Qsort () method (JSArray.cpp source)

V8 's Array.js source code about the sort part Https://github.com/v8/v8.git

function Innerarraysort (array, length, comparefn) {//In-place QuickSort algorithm.
  For short (length <=) arrays, insertion the sort is used for efficiency. ... var insertionsort = function Insertionsort (A, from, to) {for (var i = from + 1; i < to; i++) {var el
      Ement = A[i];
        for (var j = i-1 J >= from; j--) {var tmp = a[j];
        var order = COMPAREFN (tmp, Element);
        if (Order > 0) {a[j + 1] = tmp;
        } else {break;
    } a[j + 1] = element;

  }
  };
    var QuickSort = function QuickSort (A, from, to) {var third_index = 0;
      while (true) {//insertion the sort is faster to short arrays.
        if (To-from <=) {Insertionsort (A, from, to);
      Return
      } if (To-from > 1000) {third_index = Getthirdindex (A, from, to);
      else {Third_index = from + ((to-from) >> 1); }//Find a pivot as the mediaN of the, last and middle element.
      var v0 = A[from];
      var v1 = a[to-1];
      var v2 = A[third_index];
      var c01 = Comparefn (V0, v1);
        if (C01 > 0) {//V1 < V0, so swap them.
        var tmp = V0;
        V0 = v1;
      V1 = tmp;
      }//V0 <= v1.
      var C02 = Comparefn (V0, v2);
        if (C02 >= 0) {//v2 <= v0 <=.
        var tmp = V0;
        V0 = v2;
        v2 = v1;
      V1 = tmp;
        else {//v0 <= v1 && v0 < v2 var C12 = comparefn (v1, v2);
          if (C12 > 0) {//V0 <= v2 < v1 var tmp = v1;
          V1 = v2;
        v2 = tmp;
      }//V0 <= v1 <= v2 A[from] = V0;
      A[TO-1] = v2;
      var pivot = v1;   var low_end = from + 1;
      Upper bound of elements lower than pivot.  var high_start = to-1;
      Lower bound of elements greater than pivot.
      A[third_index] = A[low_end]; A[low_end] = pivot;
      From low_end to I are elements equal to pivot.
      From I to High_start are elements that haven ' t been compared.
        Partition:for (var i = low_end + 1; i < High_start; i++) {var element = A[i];
        var order = Comparefn (element, pivot);
          if (Order < 0) {A[i] = A[low_end];
          A[low_end] = element;
        low_end++;
            else if (Order > 0) {do {high_start--;
            if (High_start = i) break partition;
            var top_elem = A[high_start];
          Order = Comparefn (Top_elem, pivot);
          while (Order > 0);
          A[i] = A[high_start];
          A[high_start] = element;
            if (Order < 0) {element = A[i];
            A[i] = A[low_end];
            A[low_end] = element;
          low_end++;
        }} if (To-high_start < Low_end-from) {QuickSort (A, high_start, to);
  to = Low_end;    else {QuickSort (A, from, low_end);
      from = High_start;
  }
    }
  }; ...... }
2. Use of the Sort method 2.1 API

Syntax: Arrayobject.sort (sortby); parameter SortBy optional, used to specify collation, must be a function.

Note: If you call the method without using parameters, the elements in the array are sorted alphabetically (in order of character encoding)

If you want to sort by other criteria, you need to provide a comparison function that compares two values, and then returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B, and the return value is as follows:

A < B, after the sorted array A before B, returns a value less than 0
A = = B, return 0
A > B, returns a value greater than 0

Quick Memory Tips

Csxiaoyao's personal memory method is: Return a value, indicate whether to exchange the order of these two numbers,a-b–> small to large,b-a–> large to small 2.2 cases 1: no parameter sort () sorting string array

var arr = new Array (5);
arr = ["Csxiaoyao", "Sunshine", "Studio", "Sunshine Studio", "Sun"];
Console.log (Arr.sort (). toString ());

Output:

Csxiaoyao,studio,sun,sunshine,sunshine Studio
2.3 Example 2: parameterless sort () sorting number array
var arr = new Array (5)
arr = [80,70,700,7,8];
Console.log (Arr.sort (). toString ());

Output:

7,70,700,8,80

Note: The results do not sort numbers by numeric size, but are sorted by string, and you must use the sort function to sort by numeric values. 2.4 Case 3: Ordering of numeric arrays of string types with parameter sort ()

var arr = new Array (5);
arr = ["", "", "", "" 7 "," 8 "];
Console.log (Arr.sort (Sortnumber). toString ());
function Sortnumber (a,b) {return
    a-b;
}

Output:

7,8,70,80,700
2.5 Case 4: The custom attribute ordering of Simple object list with parameter sort ()
var objectList = new Array ();
function Person (name,age) {
    this.name=name;
    this.age=age;
}
Objectlist.push (New person (' Csxiaoyao ',));
Objectlist.push (New person (' Sunshine ',));
Objectlist.push (New person (' Sunjianfeng ', num));
By age from small to large sort
objectlist.sort (function (a,b) {return
    a.age-b.age;
});
for (Var i=0;i<objectlist.length;i++) {
    console.log (objectlist[i].name+ "" +objectlist[i].age);
}

Output:

Csxiaoyao
Sunshine
Sunjianfeng 26
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.