The principle of sorted sort method of array in JS

Source: Internet
Author: User

Recently in Baidu's project to use the array to sort, of course, the first natural thought of the array of the sort method, this method is very simple to apply, roughly as follows:

  code is as follows copy code
 window.onload=function () {
         var arr=[2,55,55,1,75,3,9,35,70,166,432,678,32,98];
        var arr2=["George", "John", "Thomas", "James", "Adrew", "Martin"];
        function Arrsort (a,b) {
             return a-b;
           }
        Console.log (Arr.sort (arrsort)); //numeric sorting requires a function, if you want to from the big row to the small, return B-a;
        Console.log (Arr2.sort ()); //Letters not required

But it suddenly occurred to me, why is the sort usage so simple, and what exactly is the principle? So I tried not to sort the array by finding the minimum value of the arrays to insert into the new array, and then deleting the smallest value in the array, updating the array, and continuing to look for the minimum insertion, so that the code is as follows:

The code is as follows Copy Code
Window.onload=function () {
var arr=[2,55,55,1,75,3,9,35,70,166,432,678,32,98];
var len=arr.length;
Console.log (Arr.join (","));
var newarr=[];
for (Var i=0;i<len;i++) {
Newarr.push (Math.min.apply (Null,arr)); Inserts the minimum value into the new array
Arr.splice (R (arr,math.min.apply (Null,arr)), 1); Delete the minimum value immediately after inserting
}
Find the location of the smallest value in the array
function R (s,v) {
For (k in s) {
if (s[k] = = v) {
return k;
}
}
}
Console.log (Newarr.join (","))
}

PS: This is just a method I wrote, the sort principle should not be like this, you can also use bubble to sort the array, the code I do not write, online a lot of. Of course, the above code just sorts the array of numbers, and for the sort of strings, you can consider the Localecompare method of the string.

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.