2

I have an array of objects, whose elements as displayed using ng-repeat from AngularJS. Each object has a priority_int integer value, and I know that I can sort the array is descending order with:

array.sort(function(a,b){
    return b.priority_int - a.priority_int;
}

Currently, I'm adding everything to the array, before sorting by priority_int in descending order, and then displaying with ng-repeat.

Out of curiousity, how can I sort every time I push an object into the array?

MMP
  • 546
  • 2
  • 5
  • 19

2 Answers2

3

Resorting the array each time you add an element will cost a heavy runtime penalty, especially since some default array.sort implementations have an O(n^2) runtime for a nearly-sorted array.

Instead, use binary search to insert new elements into the correct position in the sorted array.

Check this related answer for more help:

Efficient way to insert a number into a sorted array of numbers?

Community
  • 1
  • 1
Zach Sadler
  • 570
  • 3
  • 11
0

The easiest way to do this would be to first find the index of where the new element should be placed. Then, you should add the element there.

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;
}

Mind you, the above function relies on an array in reverse sorted order.

Examples:

addToReverseSortedArray([5,4,3], 6); // [6,5,4,3]
addToReverseSortedArray([1,0,0,0], 10); // [10,1,0,0,0]
royhowie
  • 11,075
  • 14
  • 50
  • 67