Sort sorting in JavaScript simulation (simple instance) _javascript tips

Source: Internet
Author: User

The principle of sorting data by sort in JavaScript

The sort () method sorts the elements of the array in situ, and returns the arrays. The sort may not be stable. The default is sorted by the Unicode code points of the string;

Syntax: Arr.sort ([comparefunction])

Parameter comparefunction

Optional. Used to specify a function to arrange in a certain order. If omitted, the element is sorted according to the Unicode bit point of the characters of the string being converted to.

If Comparefunction (A, b) is less than 0, then a will be arranged before B;

If Comparefunction (A, B) equals 0, the relative position of A and B is unchanged. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers will follow

If Comparefunction (A, b) is greater than 0, B is arranged before a.

The elements in the array are arranged in a small order of
 var arr=[11,55,22,45,16,87];

  Arr.sort (function (a,b) {return
    a-b;
  });
  Console.log (arr);

Second, the simulation of JavaScript internal data sorting principle

Sortself (Arr,function (a,b) {return
    a-b;
  });
  Console.log (arr);

 function Sortself (ARRAY,FN) {for
    (var i = 0; i < array.length-1; i++) {
      var issorted=true;//default is sorted for
      (v) Ar j = 0; J < Array.length-1-i; J + +) {
        //Call function
        if (FN (array[j],array[j+1]) >0) {//
          Exchange two variables
          var temp=array[j];
          ARRAY[J]=ARRAY[J+1];
          Array[j+1]=temp;
          Issorted=false
        }
      }
      if (issorted) {break;}}}
  

The above simulation JavaScript in the sort order (simple example) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.