JS simulation to implement the sort method of Array

Source: Internet
Author: User

The array object of JavaScript has an sort method to sort array elements. This method is sorted in ascending order by ASCII characters of array items.
For example, [6, 7, 9, 1,-1]. Sort (); after execution, the array is changed to [-, 6, 7, 9].

This method cannot be executed well if you need to sort the strings in descending order or not.

Of course, sort has an optional parameter, which can help us solve this problem. By passing in a function for sort, sort sorts the returned values of the function.

Array: This function is used to pass in two elements in the array by default. For example, if a and B are passed in, if the return value of the function is greater than 0, the sorting method is B and A. If the return value is less than 0, the sorting result is a and B.

The specific meaning is hard to explain. I didn't understand how the sort was sorted at the beginning.

If you know the implementation process, the sorting principle is clear.

The implementation of sort is actually a simple Bubble sorting.

I even simulated it today. You must understand the sort principle when you understand this function.
[Ctrl + A select all Note: If you need to introduce external JS, You need to refresh it to execute]

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.