Home > Web Front-end > JS Tutorial > body text

Principle analysis of array sorting sort method in js_javascript skills

WBOY
Release: 2016-05-16 16:31:00
Original
1538 people have browsed it

This article analyzes the principle of array sorting sort method in js through examples. Share it with everyone for your reference. The specific analysis is as follows:

Recently, in a Baidu project, I have to sort arrays. Of course, I naturally thought of the sort method of arrays at the beginning. The application of this method is very simple, roughly as follows:

Copy code The code is as follows:
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)); //Number sorting requires a function. If you want to sort from large to small, return b-a;
          console.log(arr2.sort()); // Letters are not required
}

But I suddenly thought, why is the usage of sort so simple and what is its principle? So I tried to sort the array without sort. The principle is to find the minimum value of the array and insert it into the new array, then delete the minimum value in the array and update After the array, continue to find the minimum value to insert, and loop like this. The code is as follows:
Copy code The code is as follows:
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 newarr.push(Math.min.apply(null,arr)); //Insert the minimum value into the new array
arr.splice(r(arr,Math.min.apply(null,arr)),1); //After insertion, delete the minimum value immediately
}
//Find the position of the minimum 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 principle of sort should not be like this. You can also use the bubble method to sort the array. I will not write the code. There are a lot of them on the Internet. Of course, the above code is only for numeric arrays. Sorting, for sorting strings, you can consider the localeCompare method of strings.

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template