Binary-search
May 23, 2021 at 12:38pm UTC
How do i sort it by Binary search?
1 2 3 4 5 6
void OrderBook::insertOrder(OrderBookEntry& order)
{
orders.push_back(order);
std::sort(orders.begin(), orders.end(),
OrderBookEntry::compareByTimestamp);
}.
May 23, 2021 at 2:18pm UTC
It sounds like orders is already sorted when you call insertOrder(). In that case, you can use binary search to find the position where order should be inserted. Then insert it there manually.
The standard library provides upper_bound() to do the binary search, but your prof may want you to write the code yourself.
http://www.cplusplus.com/reference/algorithm/upper_bound/
To insert the new item, you have to copy the old items to the right. You can use copy_backward() for that:
http://www.cplusplus.com/reference/algorithm/copy_backward/
Others on the forum may know of an easier way.
Topic archived. No new replies allowed.