Simulate sort sorting (simple example) in javascript and javascriptsort

Source: Internet
Author: User
Tags sorts

Simulate sort sorting (simple example) in javascript and javascriptsort

I. How sort sorts data in javascript

The sort () method sorts the elements of the array in the same place and returns the array. Sort may not be stable. By default, it is sorted by the Unicode code position of the string;

Syntax: arr. sort ([compareFunction])

Parameter compareFunction

Optional. A function that is used to specify the order. If omitted, the elements are sorted according to the Unicode position of the characters converted to the string.

If compareFunction (a, B) is smaller than 0, a is arranged before B;

If compareFunction (a, B) is equal to 0, the relative positions of a and B remain unchanged. Note: The ECMAScript standard does not guarantee this line, and not all browsers will comply with this line.

If compareFunction (a, B) is greater than 0, B is arranged before.

// Arrange the elements in the array in the ascending order of var arr = [,]; arr. sort (function (a, B) {return a-B;}); console. log (arr );

Ii. Simulate the principle of sorting data in javascript

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; // the order for (var j = 0; j <array. length-1-i; j ++) {// call the function if (fn (array [j], array [j + 1])> 0) {// swap two variables var temp = array [j]; array [j] = array [j + 1]; array [j + 1] = temp; isSorted = false ;}}if (isSorted) {break ;}}}

The above sort sorting (simple example) in the simulated javascript is all the content shared by the editor. I hope it can be a reference for you and a lot of support for helping customers.

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.