Not-Steve
Not-Steve

Reputation: 1

Add to list then sort vs FindLastIndex then insert

I have a List of items sorted a property. i want to add another item to the list and still get a sorted list. i see 2 simple ways to do this but which is faster/ better?

Or is there another way that i do not know of?

Upvotes: 0

Views: 134

Answers (2)

Elis
Elis

Reputation: 91

Here is some interesting facts:

Option 1: 1) Inserting all items in list. Just inserting will take O(1). 2) Sort the list by some sorting algorithm. Fastest worst case is O(n log n).

Option 2: 1) Find. Using Binary search, worst case is O(log n), but not your case :) (Your case using FindLastIndex which is a predicate: This method is an O(n) operation, where n is the Length of array.) 2) Insert the number would be O(1).

Basically if you want to add items just in the last index second option definitely is faster and the best option.

Upvotes: 2

Ahmad Alkaraki
Ahmad Alkaraki

Reputation: 106

in my opinion I think

Use FindLastIndex then Insert item on index + 1

should be better because in resorting at least process will walk over the list once :)

Upvotes: 0

Related Questions