Home > Web Front-end > JS Tutorial > Simulate sort sorting in javascript

Simulate sort sorting in javascript

怪我咯
Release: 2017-03-30 09:52:07
Original
1096 people have browsed it

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);
Copy after login

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;
      }
    }
  }
Copy after login



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!

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