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?

2
  • 1
    Create a function that takes in a value and then pushes it and sorts, and use that for your pushes? Commented Feb 24, 2015 at 21:19
  • You can do the sorting with the ng-repeat Commented Feb 24, 2015 at 21:22

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.