javascript中快速稳定的排序算法实现

时间:2009-09-15 14:40:32

标签: javascript algorithm sorting

我正在寻找一个大约200-300个对象的数组,对特定键和给定顺序(asc / desc)进行排序。结果的顺序必须一致且稳定。

什么是最好的算法,你可以在javascript中提供它的实现示例吗?

谢谢!

16 个答案:

答案 0 :(得分:107)

可以从非稳定的排序函数中获得稳定的排序。

在排序之前,您将获得所有元素的位置。 在排序条件下,如果两个元素相等,则按位置排序。

多田!你有一个稳定的类别。

如果您想了解有关此技术的更多信息以及如何实施该技术,我已在我的博客上撰写了一篇关于它的文章:http://blog.vjeux.com/2010/javascript/javascript-sorting-table.html

答案 1 :(得分:32)

由于您正在寻找稳定的东西,合并排序应该这样做。

http://www.stoimen.com/blog/2010/07/02/friday-algorithms-javascript-merge-sort/

该代码可在以上网站找到:

function mergeSort(arr)
{
    if (arr.length < 2)
        return arr;

    var middle = parseInt(arr.length / 2);
    var left   = arr.slice(0, middle);
    var right  = arr.slice(middle, arr.length);

    return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right)
{
    var result = [];

    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else {
            result.push(right.shift());
        }
    }

    while (left.length)
        result.push(left.shift());

    while (right.length)
        result.push(right.shift());

    return result;
}

编辑:

根据这个post,它看起来像某些实现中的Array.Sort使用合并排序。

答案 2 :(得分:16)

我知道这个问题已经回答了一段时间,但我碰巧在我的剪贴板中有一个很好的稳定合并排序实现Array和jQuery,所以我会分享它,希望未来的一些搜索者可能会找到它是有用的。

它允许您像普通Array.sort实现一样指定自己的比较函数。

实施

// Add stable merge sort to Array and jQuery prototypes
// Note: We wrap it in a closure so it doesn't pollute the global
//       namespace, but we don't put it in $(document).ready, since it's
//       not dependent on the DOM
(function() {

  // expose to Array and jQuery
  Array.prototype.mergeSort = jQuery.fn.mergeSort = mergeSort;

  function mergeSort(compare) {

    var length = this.length,
        middle = Math.floor(length / 2);

    if (!compare) {
      compare = function(left, right) {
        if (left < right)
          return -1;
        if (left == right)
          return 0;
        else
          return 1;
      };
    }

    if (length < 2)
      return this;

    return merge(
      this.slice(0, middle).mergeSort(compare),
      this.slice(middle, length).mergeSort(compare),
      compare
    );
  }

  function merge(left, right, compare) {

    var result = [];

    while (left.length > 0 || right.length > 0) {
      if (left.length > 0 && right.length > 0) {
        if (compare(left[0], right[0]) <= 0) {
          result.push(left[0]);
          left = left.slice(1);
        }
        else {
          result.push(right[0]);
          right = right.slice(1);
        }
      }
      else if (left.length > 0) {
        result.push(left[0]);
        left = left.slice(1);
      }
      else if (right.length > 0) {
        result.push(right[0]);
        right = right.slice(1);
      }
    }
    return result;
  }
})();

使用示例

var sorted = [
  'Finger',
  'Sandwich',
  'sandwich',
  '5 pork rinds',
  'a guy named Steve',
  'some noodles',
  'mops and brooms',
  'Potato Chip Brand® chips'
].mergeSort(function(left, right) {
  lval = left.toLowerCase();
  rval = right.toLowerCase();

  console.log(lval, rval);
  if (lval < rval)
    return -1;
  else if (lval == rval)
    return 0;
  else
    return 1;
});

sorted == ["5 pork rinds", "a guy named Steve", "Finger", "mops and brooms", "Potato Chip Brand® chips", "Sandwich", "sandwich", "some noodles"];

答案 3 :(得分:14)

使用ES2017功能(如箭头功能和解构)的相同内容的更短版本:

功能

var stableSort = (arr, compare) => arr
  .map((item, index) => ({item, index}))
  .sort((a, b) => compare(a.item, b.item) || a.index - b.index)
  .map(({item}) => item)

它接受输入数组和比较函数:

stableSort([5,6,3,2,1], (a, b) => a - b)

它还会返回新数组,而不是像内置Array.sort()函数那样进行就地排序。

测试

如果我们采用以下input数组,最初按weight排序:

// sorted by weight
var input = [
  { height: 100, weight: 80 },
  { height: 90, weight: 90 },
  { height: 70, weight: 95 },
  { height: 100, weight: 100 },
  { height: 80, weight: 110 },
  { height: 110, weight: 115 },
  { height: 100, weight: 120 },
  { height: 70, weight: 125 },
  { height: 70, weight: 130 },
  { height: 100, weight: 135 },
  { height: 75, weight: 140 },
  { height: 70, weight: 140 }
]

然后使用height按<{1}}对其进行排序:

stableSort

结果:

stableSort(input, (a, b) => a.height - b.height)

然而,使用内置// Items with the same height are still sorted by weight // which means they preserved their relative order. var stable = [ { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 70, weight: 140 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 80 }, { height: 100, weight: 100 }, { height: 100, weight: 120 }, { height: 100, weight: 135 }, { height: 110, weight: 115 } ] (在Chrome / NodeJS中)对相同的input数组进行排序:

Array.sort()

返回:

input.sort((a, b) => a.height - b.height)

资源

更新

  

var unstable = [ { height: 70, weight: 140 }, { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 100 }, { height: 100, weight: 80 }, { height: 100, weight: 135 }, { height: 100, weight: 120 }, { height: 110, weight: 115 } ] 现在在V8 v7.0 / Chrome 70中保持稳定!

     

以前,V8使用不稳定的QuickSort用于包含10个以上元素的数组。现在,我们使用稳定的TimSort算法。

     

source

答案 4 :(得分:9)

根据in this answer所做的断言,您可以使用以下polyfill实现稳定排序,而不管本机实现如何:

&#13;
&#13;
// ECMAScript 5 polyfill
Object.defineProperty(Array.prototype, 'stableSort', {
  configurable: true,
  writable: true,
  value: function stableSort (compareFunction) {
    'use strict'

    var length = this.length
    var entries = Array(length)
    var index

    // wrap values with initial indices
    for (index = 0; index < length; index++) {
      entries[index] = [index, this[index]]
    }

    // sort with fallback based on initial indices
    entries.sort(function (a, b) {
      var comparison = Number(this(a[1], b[1]))
      return comparison || a[0] - b[0]
    }.bind(compareFunction))

    // re-map original array to stable sorted values
    for (index = 0; index < length; index++) {
      this[index] = entries[index][1]
    }
    
    return this
  }
})

// usage
const array = Array(500000).fill().map(() => Number(Math.random().toFixed(4)))

const alwaysEqual = () => 0
const isUnmoved = (value, index) => value === array[index]

// not guaranteed to be stable
console.log('sort() stable?', array
  .slice()
  .sort(alwaysEqual)
  .every(isUnmoved)
)
// guaranteed to be stable
console.log('stableSort() stable?', array
  .slice()
  .stableSort(alwaysEqual)
  .every(isUnmoved)
)

// performance using realistic scenario with unsorted big data
function time(arrayCopy, algorithm, compare) {
  var start
  var stop
  
  start = performance.now()
  algorithm.call(arrayCopy, compare)
  stop = performance.now()
  
  return stop - start
}

const ascending = (a, b) => a - b

const msSort = time(array.slice(), Array.prototype.sort, ascending)
const msStableSort = time(array.slice(), Array.prototype.stableSort, ascending)

console.log('sort()', msSort.toFixed(3), 'ms')
console.log('stableSort()', msStableSort.toFixed(3), 'ms')
console.log('sort() / stableSort()', (100 * msSort / msStableSort).toFixed(3) + '%')
&#13;
&#13;
&#13;

运行上面执行的效果测试,stableSort()似乎在Chrome版本59-61上以sort()的约57%的速度运行。

.bind(compareFunction)内的包装匿名函数上使用stableSort(),通过将每个调用分配给上下文而避免对compareFunction的不需要的范围引用,从而提高了约38%的相对性能

更新

将三元运算符更改为逻辑短路,其平均表现更好(似乎效率差异为2-3%)。

答案 5 :(得分:5)

下面通过应用提供的compare函数对提供的数组进行排序,当compare函数返回0时返回原始索引比较:

var names = [
	{ surname: "Williams", firstname: "Mary" },
	{ surname: "Doe", firstname: "Mary" }, 
	{ surname: "Johnson", firstname: "Alan" }, 
	{ surname: "Doe", firstname: "John" }, 
	{ surname: "White", firstname: "John" }, 
	{ surname: "Doe", firstname: "Sam" }
]

function stableSort(arr, compare) {
    var original = arr.slice(0);

    arr.sort(function(a, b){
        var result = compare(a, b);
        return result === 0 ? original.indexOf(a) - original.indexOf(b) : result;
    });
	
    return arr;
}

stableSort(names, function(a, b) { 
	return a.surname > b.surname ? 1 : a.surname < b.surname ? -1 : 0;
})

names.forEach(function(name) {
	console.log(name.surname + ', ' + name.firstname);
});

以下示例按姓氏对名称数组进行排序,保留相同姓氏的顺序:

{{1}}

答案 6 :(得分:3)

这是一个稳定的实现。它使用本机排序,但在元素比较相等的情况下,使用原始索引位置断开关系。

function stableSort(arr, cmpFunc) {
    //wrap the arr elements in wrapper objects, so we can associate them with their origional starting index position
    var arrOfWrapper = arr.map(function(elem, idx){
        return {elem: elem, idx: idx};
    });

    //sort the wrappers, breaking sorting ties by using their elements orig index position
    arrOfWrapper.sort(function(wrapperA, wrapperB){
        var cmpDiff = cmpFunc(wrapperA.elem, wrapperB.elem);
        return cmpDiff === 0 
             ? wrapperA.idx - wrapperB.idx
             : cmpDiff;
    });

    //unwrap and return the elements
    return arrOfWrapper.map(function(wrapper){
        return wrapper.elem;
    });
}

非全面测试

var res = stableSort([{a:1, b:4}, {a:1, b:5}], function(a, b){
    return a.a - b.a;
});
console.log(res);

another answer提到了这一点,但没有发布代码。

但是,根据我的benchmark,它并不快。我修改了merge sort impl以接受自定义比较器功能,而且速度要快得多。

答案 7 :(得分:3)

您也可以使用Timsort。这是一个非常复杂的算法(400多行,因此这里没有源代码),所以请参阅Wikipedia's description或使用现有的JavaScript实现之一:

GPL 3 implementation。打包为Array.prototype.timsort。似乎是对Java代码的精确重写。

Public domain implementation作为教程,示例代码仅显示其对整数的使用。

Timsort是一种高度优化的mergesort和shuffle排序混合体,是Python和Java(1.7+)中的默认排序算法。这是一个复杂的算法,因为它对许多特殊情况使用不同的算法。但结果是在各种情况下它都非常快。

答案 8 :(得分:1)

http://www.stoimen.com/blog/2010/07/02/friday-algorithms-javascript-merge-sort/

中的一个简单的mergeSort
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];

function mergeSort(arr)
{
    if (arr.length < 2)
         return arr;

    var middle = parseInt(arr.length / 2);
    var left   = arr.slice(0, middle);
    var right  = arr.slice(middle, arr.length);

    return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right)
{
     var result = [];

    while (left.length && right.length) {
         if (left[0] <= right[0]) {
             result.push(left.shift());
         } else {
            result.push(right.shift());
         }
    }

    while (left.length)
        result.push(left.shift());

    while (right.length)
        result.push(right.shift());

    return result;
}

console.log(mergeSort(a));

答案 9 :(得分:0)

我必须按任意列对多维数组进行排序,然后按另一列进行排序。我用这个函数来排序:

function sortMDArrayByColumn(ary, sortColumn){

    //Adds a sequential number to each row of the array
    //This is the part that adds stability to the sort
    for(var x=0; x<ary.length; x++){ary[x].index = x;}

    ary.sort(function(a,b){
        if(a[sortColumn]>b[sortColumn]){return 1;}
        if(a[sortColumn]<b[sortColumn]){return -1;}
        if(a.index>b.index){
            return 1;
        }
        return -1;
    });
}

请注意,ary.sort永远不会返回零,这是&#34; sort&#34;的一些实现。功能做出可能不正确的决定。

这也非常快。

答案 10 :(得分:0)

以下是使用 MERGE SORT 的原型方法扩展JS默认Array对象的方法。此方法允许对特定键(第一个参数)和给定顺序进行排序(&#39; asc&#39; /&#39; desc&#39;作为第二个参数)

&#13;
&#13;
Array.prototype.mergeSort = function(sortKey, direction){
  var unsortedArray = this;
  if(unsortedArray.length < 2) return unsortedArray;

  var middle = Math.floor(unsortedArray.length/2);
  var leftSubArray = unsortedArray.slice(0,middle).mergeSort(sortKey, direction);
  var rightSubArray = unsortedArray.slice(middle).mergeSort(sortKey, direction);

  var sortedArray = merge(leftSubArray, rightSubArray);
  return sortedArray;

  function merge(left, right) {
    var combined = [];
    while(left.length>0 && right.length>0){
      var leftValue = (sortKey ? left[0][sortKey] : left[0]);
      var rightValue = (sortKey ? right[0][sortKey] : right[0]);
      combined.push((direction === 'desc' ? leftValue > rightValue : leftValue < rightValue) ? left.shift() : right.shift())
    }
    return combined.concat(left.length ? left : right)
  }
}
&#13;
&#13;
&#13;

您可以将上述代码段放入浏览器控制台,然后尝试:

,自行测试
var x = [2,76,23,545,67,-9,12];
x.mergeSort(); //[-9, 2, 12, 23, 67, 76, 545]
x.mergeSort(undefined, 'desc'); //[545, 76, 67, 23, 12, 2, -9]

或者根据对象数组中的特定字段进行排序:

var y = [
  {startTime: 100, value: 'cat'},
  {startTime: 5, value: 'dog'},
  {startTime: 23, value: 'fish'},
  {startTime: 288, value: 'pikachu'}
]
y.mergeSort('startTime');
y.mergeSort('startTime', 'desc');

答案 11 :(得分:0)

所以我需要对我的React + Redux应用程序进行稳定排序,而Vjeux的答案在这里帮助了我。但是,我的(通用)解决方案似乎与我到目前为止看到的其他解决方案不同,所以我分享它以防其他人有匹配的用例:

  • 我真的只想要一些类似于sort() API的东西,我可以传递一个比较器函数。
  • 有时我可以就地排序,有时候我的数据是不可变的(因为Redux)而我需要一个排序副本。所以我需要为每个用例提供稳定的排序功能。
  • ES2015。

我的解决方案是创建一个indices的类型化数组,然后使用比较函数根据待排序数组对这些索引进行排序。然后我们可以使用排序的indices对原始数组进行排序或在单个传递中创建排序副本。如果这让人感到困惑,可以这样想:你通常会传递比较函数,如:

(a, b) => { 
  /* some way to compare a and b, returning -1, 0, or 1 */ 
};

您现在改为使用:

(i, j) => { 
  let a = arrayToBeSorted[i], b = arrayToBeSorted[j]; 
  /* some way to compare a and b, returning -1 or 1 */
  return i - j; // fallback when a == b
}

速度快;它基本上是内置的排序算法,最后加上两个线性通道,还有一个额外的指针间接开销层。

很高兴收到有关此方法的反馈。以下是我对它的全面实现:

/**
 * - `array`: array to be sorted
 * - `comparator`: closure that expects indices `i` and `j`, and then
 *   compares `array[i]` to `array[j]` in some way. To force stability,
 *   end with `i - j` as the last "comparison".
 * 
 * Example:
 * ```
 *  let array = [{n: 1, s: "b"}, {n: 1, s: "a"}, {n:0, s: "a"}];
 *  const comparator = (i, j) => {
 *    const ni = array[i].n, nj = array[j].n;
 *    return ni < nj ? -1 :
 *      ni > nj ? 1 :
 *        i - j;
 *  };
 *  stableSortInPlace(array, comparator);
 *  // ==> [{n:0, s: "a"}, {n:1, s: "b"}, {n:1, s: "a"}]
 * ```
 */
function stableSortInPlace(array, comparator) {
  return sortFromIndices(array, findIndices(array, comparator));
}

function stableSortedCopy(array, comparator){
  let indices = findIndices(array, comparator);
  let sortedArray = [];
  for (let i = 0; i < array.length; i++){
    sortedArray.push(array[indices[i]]);
  }
  return sortedArray;
}

function findIndices(array, comparator){
  // Assumes we don't have to worry about sorting more than 
  // 4 billion elements; if you know the upper bounds of your
  // input you could replace it with a smaller typed array
  let indices = new Uint32Array(array.length);
  for (let i = 0; i < indices.length; i++) {
    indices[i] = i;
  }
  // after sorting, `indices[i]` gives the index from where
  // `array[i]` should take the value from, so to sort
  // move the value at at `array[indices[i]]` to `array[i]`
  return indices.sort(comparator);
}

// If I'm not mistaken this is O(2n) - each value is moved
// only once (not counting the vacancy temporaries), and 
// we also walk through the whole array once more to check
// for each cycle.
function sortFromIndices(array, indices) {
  // there might be multiple cycles, so we must
  // walk through the whole array to check.
  for (let k = 0; k < array.length; k++) {
    // advance until we find a value in
    // the "wrong" position
    if (k !== indices[k]) {
      // create vacancy to use "half-swaps" trick,
      // props to Andrei Alexandrescu
      let v0 = array[k];
      let i = k;
      let j = indices[k];
      while (j !== k) {
        // half-swap next value
        array[i] = array[j];
        // array[i] now contains the value it should have,
        // so we update indices[i] to reflect this
        indices[i] = i;
        // go to next index
        i = j;
        j = indices[j];
      }
      // put original array[k] back in
      // and update indices
      array[i] = v0;
      indices[i] = i;
    }
  }
  return array;
}

答案 12 :(得分:0)

我知道这个答案已经很多了。我只是想为任何登陆这里寻求帮助的人发布快速的TS实施。

export function stableSort<T>( array: T[], compareFn: ( a: T, b: T ) => number ): T[] {
    const indices = array.map( ( x: T, i: number ) => ( { element: x, index: i } ) );

    return indices.sort( ( a, b ) => {
        const order = compareFn( a.element, b.element );
        return order === 0 ? a.index - b.index : order;
    } ).map( x => x.element );
}

该方法不再像本地排序那样就地运行。我还想指出,这不是最有效的。它添加了两个O(n)阶的循环。尽管排序本身很可能是O(n log(n)),所以它小于O。

提到的某些解决方案性能更高,以为这可能是更少的代码,也使用内部Array.prototype.sort

(对于Javascript解决方案,只需删除所有类型)

答案 13 :(得分:0)

根据v8 dev blogcaniuse.com Array.sort已经按照现代浏览器中的规范要求已经稳定,因此您无需推出自己的解决方案。 我能看到的唯一例外是Edge,它应该很快移到铬上并也支持它。

答案 14 :(得分:0)

function sort(data){
    var result=[];
    var array = data;
    const array2=data;
    const len=array2.length;
    for(var i=0;i<=len-1;i++){
    var min = Math.min.apply(Math,array)
    result.push(min);
    var index=array.indexOf(min)
    array.splice(index,1);
    }
    return result;
}   
sort([9,8,5,7,9,3,9,243,4,5,6,3,4,2,4,7,4,9,55,66,33,66]);

答案 15 :(得分:-1)

Counting Sort比合并排序更快(它在O(n)时间内执行)并且它用于整数。

Math.counting_sort = function (m) {
    var i
    var j
    var k
    var step
    var start
    var Output
    var hash
    k = m.length
    Output = new Array ()
    hash = new Array ()
    // start at lowest possible value of m
    start = 0
    step = 1
    // hash all values
    i = 0
    while ( i < k ) {
        var _m = m[i]
        hash [_m] = _m
        i = i + 1
    }
    i = 0
    j = start
    // find all elements within x
    while ( i < k ) {
        while ( j != hash[j] ) {
            j = j + step
        }
        Output [i] = j
        i = i + 1
        j = j + step
    }
    return Output
}

示例:

var uArray = new Array ()<br/>
var sArray = new Array ()<br/><br/>
uArray = [ 10,1,9,2,8,3,7,4,6,5 ]<br/>
sArray = Math.counting_sort ( uArray ) // returns a sorted array