Sorting Magazines and Boxes
Abstract
It is a rainy Sunday. Agata has decided to sort the magazines on her shelf. Because the magazines are quite thin, she refuses to insert one between two others, preferring to move them only to the ends of the shelf. She has conceived a strategy for this but is unsure of its efficiency. Meanwhile, in the adjacent room, her three-year-old son, Szymon, has just finished his Montessori tower puzzle and is figuring out how to put it away. He has adopted a very intuitive approach to nesting the boxes, though he is not certain it will ultimately succeed.
Agata and Szymon are employing very primitive strategies. While many sorting algorithms are remarkably simple to explain and implementβspecifically, the class of in-place sorting algorithms with worst-case and average-case running time and constant space requirements (e.g., Bubble Sort, Gnome Sort)βthe strategies discussed here offer a unique perspective on βintuitiveβ sorting. Our contribution aims to enrich the field of simple sorting algorithms. Interestingly, determining the exact worst-case complexity of some of the proposed algorithms remains an open problem.
Keywords and phrases:
Sorting algorithm, analysis of algorithms, intuitive sortingFunding:
Gabriele Fici: Supported by MIUR project PRIN 2022 APML β 20229BCXNW.Copyright and License:
2012 ACM Subject Classification:
Theory of computation Sorting and searchingAcknowledgements:
We would like to thank all the participants of the Workshop Frontiers of String Algorithms and Bioinformatics, held at Birkbeck, London, UK, on Feb. 7, 2024, for useful discussions. The third author is indebted to his high school computer science teacher, Ms. Alina GoΕciniak, for introducing him to Naive Magazine Sort. He also thanks Jakub Pachocki for helpful discussions regarding Szymonβs sorting algorithm.Editor:
John IaconoSeries and Publisher:
Leibniz International Proceedings in Informatics, Schloss Dagstuhl β Leibniz-Zentrum fΓΌr Informatik
1 Introduction
Agata has magazines on her shelf. She wants to sort them according to her preferred orderβfor example, by issue number. Since magazines are thin, it is difficult to insert one between two others. Agata is therefore trying to devise a strategy that allows her to insert magazines only from the ends of the shelf.
Initially, Agata considers the following simple strategy:
βI pick the magazines from the shelf one by one and move them to a second shelf, inserting each magazine at the left end if it is smaller than the previous one, or at the right end otherwise.β
Once all magazines are moved, the first shelf becomes empty, allowing her to start a second round with the same strategyβinverting the roles of the two shelvesβif the magazines are not yet sorted. This strategy is presented in the pseudocode below. Queue contains the magazines on the first shelf, and the double-ended queue (deque) represents the second shelf. We use standard queue operations: PopFront (removes and returns the first element), PushFront (inserts an element at the front), and PushBack (inserts an element at the back).
In theory, there is no difference between theory and practice; in practice, there is111This quote is often attributed to baseball player Yogi Berra.. When Agata considers how to implement her strategy concretely, she realizes that because the magazines are tall and thin, they cannot stand on their own. She would need an assistant to hold the magazines on one shelf while she manages the other.
The only other person home is her three-year-old son, Szymon, who is playing in the adjacent room. Agata must therefore improve her strategy. She realizes that because the shelves are in the corner of the room, the magazines are supported by the wall on the right end. Agata recalls reading that space can be used for multiple purposes simultaneously [4]. If she could eliminate the second shelf by reusing the space of the first shelf, she could support the magazines from the left end with one hand while using the other to pick and reinsert magazines.
After some thought, Agata arrives at a new realization of her strategy:
βI scan all the magazines from left to right. Each time I find a magazine that is smaller than the one immediately on its left, I mark (by pulling it slightly towards me). Once I have finished scanning, I take each marked magazine in the order it was marked and reinsert them at the left end of the shelf.β
This realization is equivalent to the first but significantly more convenient to perform manually. The following pseudocode illustrates this strategy using a single shelf , implemented as a doubly-linked list with operations: Front (returns the first element), Next (returns the subsequent element), and MoveToFront (removes a given element from its current position and reinserts it at the front of the list). We utilize a queue to store pointers to the marked elements, allowing for reinsertion.
Example 1.
For convenience, letβs denote the magazines by their rank in the sorted order:
Round 0: .
Agata marks magazines and , as these are the elements preceded by a larger one. She then picks the marked elements one by one, in the order they were encountered from left to right, and reinserts them at the left end of the shelf. The resulting order is:
Round 1: .
After ten rounds, Agata starts to wonder if this procedure will ever terminate. Is she simply repeating the same sequence of moves? However, the last three magazines are now in the correct order, which sounds promising⦠She decides to persevere, and finally, at the end of the 20th round, the magazines are completely sorted!
Example 2 (Example 1 continued).
Agata will finish after 20 rounds. The sequence of rounds demonstrates the gradual movement of smaller elements toward the front and the emergence of sorted suffixes.
Round β 1: (7, 8, 2, 1, 3, 4, 5, 6, 10, 9)
Round β 2: (9, 1, 2, 7, 8, 3, 4, 5, 6, 10)
Round β 3: (3, 1, 9, 2, 7, 8, 4, 5, 6, 10)
Round β 4: (4, 2, 1, 3, 9, 7, 8, 5, 6, 10)
Round β 5: (5, 7, 1, 2, 4, 3, 9, 8, 6, 10)
Round β 6: (6, 8, 3, 1, 5, 7, 2, 4, 9, 10)
Round β 7: (2, 1, 3, 6, 8, 5, 7, 4, 9, 10)
Round β 8: (4, 5, 1, 2, 3, 6, 8, 7, 9, 10)
Round β 9: (7, 1, 4, 5, 2, 3, 6, 8, 9, 10)
Round 10: (2, 1, 7, 4, 5, 3, 6, 8, 9, 10)
Round 11: (3, 4, 1, 2, 7, 5, 6, 8, 9, 10)
Round 12: (5, 1, 3, 4, 2, 7, 6, 8, 9, 10)
Round 13: (6, 2, 1, 5, 3, 4, 7, 8, 9, 10)
Round 14: (3, 1, 2, 6, 5, 4, 7, 8, 9, 10)
Round 15: (4, 5, 1, 3, 2, 6, 7, 8, 9, 10)
Round 16: (2, 1, 4, 5, 3, 6, 7, 8, 9, 10)
Round 17: (3, 1, 2, 4, 5, 6, 7, 8, 9, 10)
Round 18: (1, 3, 2, 4, 5, 6, 7, 8, 9, 10)
Round 19: (2, 1, 3, 4, 5, 6, 7, 8, 9, 10)
Round 20: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10).
In each round, Agata first scans all the magazines to decide which ones to mark. In our example, Agata marked and subsequently moved 52 magazines across all rounds. Assuming it takes her 1 second to check if a magazine should be marked, 1 second to mark it, and 2 seconds to move it, the total time spent was secondsβless than 6 minutes to sort her 10 magazines.
Agata wonders whether she was simply lucky this time, or if her strategy is guaranteed to workβ¦ Then she pauses: βIs this marking phase really necessary after all?β She devises a final improvement:
βI scan the magazines from left to right. Whenever I find a magazine smaller than the one on its left, I immediately pick and reinsert it at the left end.β
This refined strategy is illustrated in the pseudocode below. In this version, the move is performed immediately, eliminating the need for a marking queue. Note that when an element is moved to the front, the next element to be checked is compared against the same that was previously to the left of .
βWell, this actually seems faster!β she thinks. Indeed, this time she finishes after only 6 rounds.
Example 3 (Example 1 continued).
We start with the same initial arrangement:
Round 0: .
In the first round, Agata picks , as it is smaller than (the element immediately to its left), and reinserts it at the beginning of the shelf. She then picks , as it is smaller than β which is now the element immediately to the left of after was moved. This process continues through the shelf. The final elements moved to the beginning of the shelf are (as 10 is on its left), then (as 10 is still on its left), and finally . This concludes the first round.
Agata completes the sorting in 6 rounds, as shown below:
In total, Agata moved 31 magazines over 6 rounds. Assuming she needs 1 second to determine if a magazine should be moved and 2 seconds to move each magazine, the total time required was secondsβless than 2 minutes to sort her 10 magazines.
At this point, we are left with several questions: Do all of Agataβs strategies always converge to the sorted list? And if so, what is the number of rounds or steps in the worst and average cases?
In the meantime, in the adjacent room, Agataβs three-year-old son, Szymon, is playing with his favorite toy: a Montessori tower (see Figure 1).
The toy consists of ten cubic boxes of different sizes. After Szymon successfully builds the tower by stacking all the cubes in decreasing order of size, he enjoys toppling. Now the boxes lie scattered across the carpet. Szymon knows that each box has one missing face, which must serve as the bottom; therefore, to put the toy away, he must nest the boxes one inside another in the correct order.
Szymon employs a simple, intuitive algorithm: First, he selects a box he assumes will be the outermost. He then picks up another box with his right hand and attempts to place it inside the first. He continues this process as long as each subsequently selected box fits within the one immediately preceding it. If the box does not fit, Szymon repeatedly removes the innermost box with his left hand until the box currently in his right hand fits inside. The boxes removed from the partial stack are returned to the carpet in a disordered fashion. The specific order in which Szymon selects the remaining boxes is not immediately evident.
The following pseudocode illustrates the strategy. The partial order of boxes is implemented as a stack , with the largest box at the bottom and the smallest at the top. The stack provides standard methods: Push (adds an element to the top), Pop (removes the top element), and Top (returns the top element). The collection of boxes remaining on the carpet supports the operations: Insert (returns a box to the collection) and RandomPick (selects a box based on Szymonβs undisclosed selection criterion).
Szymon is always able to order all the boxes within a few minutes, even though it is not immediately obvious to his parents that his algorithm is guaranteed to terminate. Moreover, the worst-case complexity of his approach may seem concerning. Was he simply lucky with the sequence of boxes he chose, or did he have some underlying intuition?
2 Analysis of magazine sorting algorithms
Let us first analyze Agataβs algorithms. In full generality, let be the number of magazines to be sorted. For simplicity, we assume magazines are identified with their ranks , though the algorithms only require a total strict order and do not assume a specific permutation of integers. We further assume all magazines are distinct.
As we have already mentioned, Naive Magazine Sort and Magazine Sort With Marking are essentially equivalent. Specifically, they perform the same number of rounds. Each round can be implemented in time linear in the number of magazines using appropriate pointer data structures: a queue and a double-ended queue for Naive Magazine Sort, and a list and a marking-queue for Magazine Sort With Marking. Thus, the crucial parameter in both algorithms is the number of rounds.
Let us analyze Magazine Sort With Marking. The algorithm consists of one or more rounds where magazines are scanned from left to right. In any given round, let be the largest element currently in a position smaller than . It follows that element is in position for every , and it will remain there after each subsequent round. In the next round, will be moved to position for some , as there is at least one element to the right of that is smaller than its predecessor and will thus be moved to the front. This demonstrates that the algorithm converges in at most rounds or total steps.
An almost-worst-case instance appears to be the permutation . For this permutation, it takes exactly rounds for to reach the final position. After the -th round, element is at position , followed by :
While the permutation seems to require rounds, we have not yet proven this theoretically. Figure 2 contains a graph showing the number of steps the algorithm performed on permutations of this type.
Β Remark 4.
We have experimentally verified that the permutation is a worst-case instance for and . For , this permutation requires 24 rounds, whereas there exist other permutations, such as , which require rounds. Similarly, it is not the worst-case instance for or .
Determining the exact complexity of Magazine Sort With Marking remains an open problem.
We now analyze the Magazine Sort No Marking algorithm. This variant performs at most rounds. To see this, let be the largest element not in the correct sorted position at the start of a round; specifically, suppose it is in position for some . By the maximality of , all elements to the right of up to position (i.e., those in position through ) must be smaller than . Consequently, these elements will be moved to the front by the end of the current round. This guarantees that will occupy its correct position by the next round.
Thus, the algorithm requires at most rounds and is therefore worst-case quadratic ( in the total number of element moves).
A worst-case instance for odd is the permutation
This instance is constructed in such a way that before the -th round, for , the element is at the beginning, while all elements greater than (the largest elements) are already correctly placed at the end. This forces the algorithm to perform exactly rounds. For example:
A similar worst-case instance for even is .
Comparison with other classic sorting algorithms.
Magazine Sort No Marking shares some characteristics with Bubble Sort, but they behave differently. In Bubble Sort, if the largest element is at the beginning, it moves to the end in one round while the relative order of the remaining elements is preserved. In Magazine Sort No Marking, the maximal element also reaches the end in one round, but the relative order of the other elements is reversed. The performance can diverge significantly: for the reverse permutation , Bubble Sort is quadratic, whereas Magazine Sort No Marking requires only one round. Furthermore, Bubble Sort is physically impractical for sorting magazines because it requires swaps or insertions in the middle of the sequence.
Selection Sort is physically compatible with the magazine model. However, Selection Sort always performs comparisons regardless of the input, while Magazine Sort No Marking can be faster on specific nearly-sorted or reversed inputs.
Insertion Sort and Gnome Sort typically run in time, where is the number of inversions. Like Bubble Sort, they perform steps for the reversed sequence βan βeasyβ case for our algorithmβand they do not fit the magazine model due to the requirement for the middle-sequence insertion.
3 Optimizing magazine sorting algorithms
The implementation of the Magazine Sort With Marking algorithm can be improved so that in each round (except for the first), the total number of operations is proportional only to the number of moved elements. The core logic remains unchanged; intuitively, during the moving phase of the current round, we can simultaneously perform the marking for the next round.
Consider a round , and let be an element that is marked by the original Magazine Sort With Marking algorithm. This implies that its predecessor, , satisfies . Now consider round . Let denote in round . We have , as otherwise would have been marked and moved in round . This implies that either or was moved in round .
In the optimized algorithm, whenever an element is removed from the list, we check if the subsequent element should be marked for the next round by comparing it with the predecessor of . This corresponds to marking when is moved. Furthermore, whenever an element is prepended to the list, we check if the element that was previously at the front should be marked for the next round. This corresponds to marking when is moved to the front.
In the first round of Optimized Magazine Sort With Marking, the marking phase is exactly the same as in Magazine Sort With Marking. The list stores all the marked elements for the current round, and the list stores all the marked elements for the next round. We then iterate through all elements of the list and move them to the front one by one. Whenever a marked element is removed from the list , we check if its successor in the list should be marked for the next phase; if so, we add it to . Additionally, when the marked element is pushed to the front of the list , we check if the previously first element of the list should be marked for the next round. In the end, becomes the new list .
Example 5.
During initialization: Agata marks magazines and .
Round 0: ; marked elements are underlined.
In the first round, Agata picks the marked elements from left to right. Upon removing an element, she checks the new neighbors; if the successor is smaller than the predecessor, she marks it. Thus, she marks when is removed. Similarly, when reinserting at the left, if she places a magazine to the left of a smaller one, she marks the smaller one. Thus, is marked when is reinserted, and is marked when is reinserted. By the end of Round 1, the shelf is:
Round 1: .
In Round 1, when element is moved, element will not be marked for Round 2, as it is already marked for Round 1 and will be moved within the same round. Next, element will be marked for Round 2. Actually, element will be marked at its new position at the same moment element is moved to the front. Overall, the shelf is ready for the second round and looks as follows:
Round 2: .
Agata continues removing marked elements, marking more as she progresses. She ends up marking and removing 52 magazines in total. However, she no longer needs to scan the entire shelf in each round.
In Optimized Magazine Sort With Marking, there is no strict correspondence between the number of rounds and the total number of steps. The algorithm performs the same number of rounds as its predecessor, but each round is faster. This is confirmed by experimental analysis in Figure 3. The upper bound of steps still applies. As a comparison-based algorithm, the classic lower bound applies. The exact complexity, however, remains an open problem.
We can similarly optimize Magazine Sort No Marking by ensuring its complexity depends only on the number of magazines effectively moved. This requires reintroducing a focused marking strategy to track elements affected by displacements.
In the first round of Optimized Magazine Sort No Marking, the initialization is identical to the previous optimized algorithm. The list stores current marked elements, and stores the marked elements for the next round. When a marked element is processed, it is smaller than its predecessor . Therefore, and all elements to its right that are smaller than are moved to the front one by one. When an element is pushed to the front, it is removed from (if present), and we check if the previously first element of the list should be marked for the next round.
Example 6.
Beginning with the initial arrangement of magazines from Example 5:
Round 0: .
In the next round, Agata picks (the first marked element) and reinserts it at the beginning, followed by . However, when Agata picks , before reinserting it, she marks (the current leftmost element) since . Similarly, she marks before reinserting , and marks before reinserting . By the end of the first round:
Round 1: (7, 9, 8, 2, 1, 3, 4, 5, 6, 10)
Processing only marked elements, Agata finishes after 5 more rounds:
| Algorithm | Lower Bound | Upper Bound |
|---|---|---|
| Magazine Sort With Marking | ||
| Optimized Magazine Sort With Marking | ||
| Magazine Sort No Marking | ||
| Optimized Magazine Sort No Marking |
The optimized Magazine Sort No Marking maintains a worst-case complexity of . However, as shown in Figure 4, it performs significantly better than the basic version and Bubble Sort on random permutations.
A summary of the complexities of magazine sorting algorithms can be found in Table 1.
4 Analysis of Montessori sorting algorithm
Let us now analyze Szymonβs algorithm in a general setting with boxes, of sizes (smallest) to (largest).
As established, the βpartial orderβ of boxes stored in Montessori Tower Random Sort functions as a stack. At each step, a box is selected from the carpet; it is pushed onto the stack if its size is smaller than the box currently on top. Otherwise, boxes are popped from the stack one by one until the top box is larger than the box to be inserted.
First, we prove that the algorithm always terminates. The set of boxes stored on the stack can be represented as a binary sequence of length where the -th bit is 1 if box is on the stack and 0 otherwise. Suppose box is selected from the carpet. The algorithmβs operations consist of zeroing all bits at positions (the pops) and setting the -th bit to 1 (the push). If the sequence is viewed as a binary counter, where the -bit is the most significant digit, then every step in the algorithm strictly increases the counterβs value. The counter starts at 0 (an empty stack) and reaches a maximum at (all boxes correctly nested). Since the counter strictly increases with each selection, the algorithm must terminate.
The binary counter argument shows there are at most distinct stack states. Unfortunately, a specific sequence of box selections can force the algorithm to visit every state. This occurs if we pick box every second step, box every second remaining step, and so on (see Figure 5).
If we measure complexity by unit operations on the stack, this behavior mirrors a binary counter counting from to . It is well known that such a counter requires bit-flips to reach the maximum value [2]. Since each bit-flip corresponds to a Push () or a Pop (), the worst-case time complexity of Montessori Tower Random Sort is .
So how is it possible that Szymon consistently orders boxes within minutes? Assuming it takes a three-year-old seconds to move one box, the worst-case scenario would require secondsβnearly three hours!
The efficiency Szymon experiences lies in the expected-time analysis. If a box is selected uniformly at random from the collection at each step, then after an expected selections, the largest box () will be picked. Once box is pushed onto the stack, the stack is cleared of all smaller elements, and box becomes the permanent bottom of the stack. The problem then reduces to sorting the remaining boxes. Inductively, the total expected number of Push operations is: . The expected number of Pop operations is also . Indeed, for , with seconds per operation, the expected time is roughly seconds, or just over 9 minutes. This aligns perfectly with the observation that Szymon finishes βwithin a few minutes.β
Comparison with other slow sorting algorithms.
Among the most famous βslowβ sorting algorithms are Bogo Sort and Bozo Sort. These algorithms perform random updates until a permutation is sorted; Bogo Sort applies a random permutation, while Bozo Sort applies a random transposition. As shown in [3], both algorithms have an average-case time complexity of . While optimized versions of these algorithms exist with complexity [1], the Montessori approach remains naturally more efficient for small due to its expected behavior.
5 Conclusion
This work shows that so-called intuitive sorting strategies admit rigorous mathematical analysis. We prove that Agataβs Magazine Sort No Marking is a physically realizable in-place sorting algorithm with worst-case running time . In contrast, Szymonβs Montessori Tower Random Sort exhibits a pronounced separation between worst-case and expected behavior: while its worst-case complexity is exponential, , its expected running time is .
For Magazine Sort With Marking, a key complexity question remains unresolved. We establish an upper bound and observe quadratic behavior in practice; however, determining whether the algorithm admits rounds in the worst case remains open.
References
- [1] Therese C. Biedl, Timothy M. Chan, Erik D. Demaine, Rudolf Fleischer, Mordecai J. Golin, James A. King, and J. Ian Munro. Fun-sortβor the chaos of unordered binary search. Discret. Appl. Math., 144(3):231β236, 2004. doi:10.1016/J.DAM.2004.01.003.
- [2] Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, 3rd Edition. MIT Press, 2009. URL: http://mitpress.mit.edu/books/introduction-algorithms.
- [3] Hermann Gruber, Markus Holzer, and Oliver Ruepp. Sorting the slow way: An analysis of perversely awful randomized sorting algorithms. In Pierluigi Crescenzi, Giuseppe Prencipe, and Geppino Pucci, editors, Fun with Algorithms, 4th International Conference, FUN 2007, Castiglioncello, Italy, June 3-5, 2007, Proceedings, volume 4475 of Lecture Notes in Computer Science, pages 183β197. Springer, 2007. doi:10.1007/978-3-540-72914-3_17.
- [4] Ian Mertz. Reusing Space: Techniques and Open Problems. Bull. Eur. Assoc. Theoret. Comput. Sci., 141:57β106, 2022.
