简体   繁体   中英

What's the best data structure to handle customers orders?

I'm thinking of queue (FIFO) but what if at some point I need to prioritize orders like for example: any order that includes milk should be pushed into the back of the queue until the milk is available and then once the milk is there I should put these orders back to its previous state.

If I use queue here, I will endup having at least bigO(n log n) time complexity.

any suggestions?

One possibility is to have two data structures. Use the FIFO to hold orders for which you have all the ingredients. Use a different data structure for orders that are waiting for something. Once that thing comes in, then you can put it in the FIFO. Adding to the end of the queue is of course O(1). Putting it back in order will require O(n) time.

If you want the order that was held to get put back into the queue in the place it should have gone, then you probably want a priority queue that uses order number (if they're sequential), or time.

Whereas it takes O(log n) time to insert into or remove from a priority queue, that's not going to be a problem unless you're processing thousands of orders a second. Insertion worst case is O(log n), but in a system such as yours where the priority queue is generally just a FIFO that has a few exceptions, expected insertion will be close to O(1).

I should clarify that most priority queue implementations (in C++, Java, Python, and other mainstream languages) use a binary heap for the backing store. Insertion into a binary heap is worst case O(log n), but analysis shows that it's usually closer to O(1). See Argument for O(1) average-case complexity of heap insertion . You could also implement a pairing heap or other advanced heap type, which has O(1) amortized insertion. But again, unless you're processing thousands of orders per second, that's probably overkill.

Another option is, when you get these exception orders, just push them to the front of the queue once all the necessary items are available. That's easy to do with a double-ended queue . How effective that will be kind of depends on how long things usually sit in the queue, and how long it takes to re-stock items that you run out of.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM