[英]How to sort array as items as added in Javascript?
我有一个对象数组,使用AngularJS的ng-repeat显示其元素。 每个对象都有一个priority_int整数值,并且我知道我可以对数组进行降序排序:
array.sort(function(a,b){
return b.priority_int - a.priority_int;
}
当前,我将所有内容添加到数组中,然后按priority_int降序排序,然后使用ng-repeat显示。
出于好奇,每次将对象推入数组时如何排序?
每次添加元素都对数组进行重新排序将耗费大量运行时间,尤其是由于某些默认array.sort实现对几乎排序的数组具有O(n ^ 2)运行时。
而是使用二进制搜索将新元素插入已排序数组中的正确位置。
查看此相关答案以获取更多帮助:
最简单的方法是首先找到应放置新元素的索引。 然后,您应该在此处添加元素。
var addToReverseSortedArray = function (arr, item) {
// our function to find the index of an element
// (or where it should be placed)
var search = function (a, i) {
var low = 0, high = a.length - 1;
while (low <= high) {
var mid = (low + high) >> 1;
if (a[mid] > i) low = mid + 1;
else if (a[mid] < i) high = mid - 1;
else return mid;
}
return low;
}
// Array.splice can actually splice 0 items
// here, we splice 0 items at index search(arr, item)
// and add `item`
arr.splice(search(arr, item), 0, item);
return arr;
}
请注意,以上函数依赖于反向排序的数组。
例子:
addToReverseSortedArray([5,4,3], 6); // [6,5,4,3]
addToReverseSortedArray([1,0,0,0], 10); // [10,1,0,0,0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.