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?
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.
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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.