I want to insert an item at an index in a sorted array. Should I be using binary search or is the below implementation good?
This below implementation does not work but the concept is clear. For some reason it gives me an error: "Value 'Double' has no member 0" but when I get rid of the && $1.0 > price
it runs but doesn't do what I want. How would I insert a value in an array between two values using the method below or any better method?
It would be an added bonus if I could update the second (quantity) value if price was already there in the array. For example if in the original array the value is (20,5) where price is 20, I would want to update that index to be (20,9).
The array is an array of Doubles that represent a price and a quantity for that price. I cannot use a dict because it needs to remain in order.
I will have more than 10K items in the array.
Here is my code.
let largeArray = [(10, 3), (20, 5), (30, 6), (40, 1), (50, 3), (60, 3)]
let price = 45
if let indexInsert = largeArray.index(where: {$0.0 < price && $1.0 > price}) {
self.sellSideOrderBook.insert(((45, 2)), at: indexInsert)
}