java - Find insertion location -
i have sorted arraylist of integers. have new integer insert arraylist. new integer has inserted @ appropriate position keep arraylist in sorted order.
i can add integer , sort using collections.sort(arraylist), arraylist big, sort taking time , need insert many times don't want end sorting multiple times eat away time.
collections.sort() has o(nlogn) (uses mergesort).
can have less time consuming, or can manually search position insert takes least time?
time high priority.
thanks in advance :)
why not go through list , add element @ appropriate position. list
sorted new list
after insertion
sorted
, o(n)
operation. there no need sort list on , on again.
edit: - there 2 things here. 1 if need find location of element should inserted current list can binary search
. inserting element in location require elements follow move 1 spot ahead create space inserted element think still more efficient inserting @ , sorting again.
Comments
Post a Comment