JavaScript中Array.sort()的底层实现及应用

JavaScript中Array.sort()的底层实现及应用

1. V8 引擎的 array.js

  js中的sort()方法用于对数组元素进行排序,具体是如何实现的?查阅资料发现,V8 引擎 sort 函数只给出了两种排序 InsertionSort 和 QuickSort,数组长度小于等于 22 的用插入排序 InsertionSort,比22大的数组则使用快速排序 QuickSort。源码中这样写道:

// In-place QuickSort algorithm.
// For short (length <= 22) arrays, insertion sort is used for efficiency.

此外,附上其他引擎的sort实现方式

Mozilla/Firefox : 归并排序(jsarray.c 源码)
Webkit :底层实现用了 C++ 库中的 qsort() 方法(JSArray.cpp 源码)

V8的array.js源码关于sort的部分 https://github.com/v8/v8.git

function InnerArraySort(array, length, comparefn) {
  // In-place QuickSort algorithm.
  // For short (length <= 22) arrays, insertion sort is used for efficiency.
  //……
  var InsertionSort = function InsertionSort(a, from, to) {
    for (var i = from + 1; i < to; i++) {
      var element = a[i];
      for (var j = i - 1; j >= from; j--) {
        var tmp = a[j];
        var order = comparefn(tmp, element);
        if (order > 0) {
          a[j + 1] = tmp;
        } else {
          break;
        }
      }
      a[j + 1] = element;
    }
  };

  var QuickSort = function QuickSort(a, from, to) {
    var third_index = 0;
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from <= 10) {
        InsertionSort(a, from, to);
        return;
      }
      if (to - from > 1000) {
        third_index = GetThirdIndex(a, from, to);
      } else {
        third_index = from + ((to - from) >> 1);
      }
      // Find a pivot as the median of first, last and middle element.
      var v0 = a[from];
      var v1 = a[to - 1];
      var v2 = a[third_index];
      var c01 = comparefn(v0, v1);
      if (c01 > 0) {
        // v1 < v0, so swap them.
        var tmp = v0;
        v0 = v1;
        v1 = tmp;
      } // v0 <= v1.
      var c02 = comparefn(v0, v2);
      if (c02 >= 0) {
        // v2 <= v0 <= v1.
        var tmp = v0;
        v0 = v2;
        v2 = v1;
        v1 = tmp;
      } else {
        // v0 <= v1 && v0 < v2
        var c12 = comparefn(v1, v2);
        if (c12 > 0) {
          // v0 <= v2 < v1
          var tmp = v1;
          v1 = v2;
          v2 = tmp;
        }
      }
      // v0 <= v1 <= v2
      a[from] = v0;
      a[to - 1] = v2;
      var pivot = v1;
      var low_end = from + 1;   // Upper bound of elements lower than pivot.
      var high_start = to - 1;  // Lower bound of elements greater than pivot.
      a[third_index] = a[low_end];
      a[low_end] = pivot;

      // From low_end to i are elements equal to pivot.
      // From i to high_start are elements that haven't been compared yet.
      partition: for (var i = low_end + 1; i < high_start; i++) {
        var element = a[i];
        var order = comparefn(element, pivot);
        if (order < 0) {
          a[i] = a[low_end];
          a[low_end] = element;
          low_end++;
        } else if (order > 0) {
          do {
            high_start--;
            if (high_start == i) break partition;
            var top_elem = a[high_start];
            order = comparefn(top_elem, pivot);
          } while (order > 0);
          a[i] = a[high_start];
          a[high_start] = element;
          if (order < 0) {
            element = a[i];
            a[i] = a[low_end];
            a[low_end] = element;
            low_end++;
          }
        }
      }
      if (to - high_start < low_end - from) {
        QuickSort(a, high_start, to);
        to = low_end;
      } else {
        QuickSort(a, from, low_end);
        from = high_start;
      }
    }
  };
  //……
}

2. sort方法的使用

2.1 api

  语法:arrayObject.sort(sortby);参数sortby可选,用于规定排序规则,必须是函数。

注:如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序(按照字符编码的顺序)

  如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:

a < b,排序后的数组中 a 在 b 前,返回一个小于 0 的值
a == b,返回 0
a > b,返回一个大于 0 的值

快速记忆秘诀

csxiaoyao的个人记忆方法为:return一个值,表示是否调换这两个数的顺序,a-b –> 小到大,b-a –> 大到小

2.2 例1:无参sort()对字符串数组排序

var arr = new Array(5);
arr = ["csxiaoyao","sunshine","studio","sunshine studio","sun"];
console.log(arr.sort().toString());

输出:

csxiaoyao,studio,sun,sunshine,sunshine studio

2.3 例2:无参sort()对Number数组排序

var arr = new Array(5)
arr = [80,70,700,7,8];
console.log(arr.sort().toString());

输出:

7,70,700,8,80

注意 : 结果没有按照数值大小对数字进行排序,而是按字符串排序,要实现按数值排序,必须使用排序函数。

2.4 例3:带参sort()对字符串类型的数值数组排序

var arr = new Array(5);
arr = ["80","70","700","7","8"];
console.log(arr.sort(sortNumber).toString());
function sortNumber(a,b){
    return a - b;
}

输出:

7,8,70,80,700

2.5 例4:带参sort()对简单对象List的自定义属性排序

var objectList = new Array();
function Person(name,age){
    this.name=name;
    this.age=age;
}
objectList.push(new Person('csxiaoyao',20));
objectList.push(new Person('sunshine',25));
objectList.push(new Person('sunjianfeng',26));
//按年龄从小到大排序
objectList.sort(function(a,b){
    return a.age-b.age;
});
for(var i=0;i" "+objectList[i].age);
}

输出:

csxiaoyao 20
sunshine 25
sunjianfeng 26

你可能感兴趣的:(javascript)