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.