1. sortThe principle of sorting data in javascript
sort() method pairThe elements of array are sorted in place and the array is returned. sort may not be stable. The default is to sort according to the Unicode code point of string;
Syntax: arr.sort([compareFunction])
Parameter compareFunction
is optional. Used to specify functions arranged in a certain order. If omitted, elements are sorted according to the Unicode positions of the characters in the converted string.
If compareFunction(a, b) is less than 0, then a will be 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 behavior, and not all browsers will comply
If compareFunction(a, b) is greater than 0, b will be sorted before a.
//将数组中的元素按照从小大的顺序排列 var arr=[11,55,22,45,16,87]; arr.sort(function(a,b){ return a-b; }); console.log(arr);
2. Simulate the principle of sorting data within 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; //默认已经排好序 for (var j = 0; j < array.length-1-i; j++) { //调用函数 if(fn(array[j],array[j+1])>0){ //交换两个变量 var temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; isSorted=false; } } if(isSorted){ break; } } }
The above is the detailed content of Simulate sort sorting in javascript. For more information, please follow other related articles on the PHP Chinese website!