Online store~10 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-912sorting
A shelf-label kiosk in a store shows the prices of one department, cheapest first. The price list changes every few minutes, and the kiosk re-sorts it each time.
Most departments have a few dozen prices. The biggest one has 100,000. The kiosk has little memory, so it sorts the list in place.
Prices are whole units. Equal prices are fine.
Write sort_prices(prices).
prices[i] is a price in units.prices in place, smallest first, and return it.Input: prices = [350, 120, 990, 120, 40]
Output: [40, 120, 120, 350, 990]A hand sort keeps the front of the list in order and inserts each next price into it.
| Next price | Larger prices it passes | List after the insert |
|---|---|---|
| 120 | 1 | [120, 350, 990, 120, 40] |
| 990 | 0 | [120, 350, 990, 120, 40] |
| 120 | 2 | [120, 120, 350, 990, 40] |
| 40 | 4 | [40, 120, 120, 350, 990] |
Seven shifts in all. For five prices that is nothing, and for 100,000 prices it would be far too many.
Input: prices = [7]
Output: [7]A list of one price is already in order.
Input: prices = [30, 20, 10]
Output: [10, 20, 30]The list is in the opposite order, which is the most work for a hand sort.
0 ≤ prices.length ≤ 100,000 (prices in one department)0 ≤ prices[i] ≤ 10,000,000 (units)A hand sort such as insertion sort shifts up to n × (n − 1) / 2 times, which is 4,999,950,000 at n = 100,000. A library sort costs about n log n comparisons, which is under 2 × 10^6 for the same n.