Permutation Search Sort: Order a List by Brute Force
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Implement a factorial-time sort that tries arrangements until one is non-decreasing, handling duplicates and empty input, and reason about its cost.
Permutation Search Sort
Some sorting methods are famous for being slow on purpose. One of them works like this: look through the possible orderings of the input one at a time, and stop at the first ordering in which every element is less than or equal to the one after it.
Write a function that takes a list of integers and returns a new list containing the same values in non-decreasing (ascending) order.
Requirements
- The returned list must contain exactly the same values as the input, with the same multiplicities. Duplicates are allowed and must all be kept.
- The returned list must be in non-decreasing order.
- An empty input returns an empty list.
- Do not modify the input list. Return a new list.
- Aim to implement the brute-force idea described above: generate arrangements of the input and test each one for sortedness. Only the returned list is checked, so the result must match what a correct sort would produce.
Constraints
0 <= len(values) <= 9, so a factorial-time search is feasible.- Each value is an integer, possibly negative, and values may repeat.
- The function returns a
List[int].
Examples
Example 1
Input: permutation_search_sort([3, 1, 2])
Output: [1, 2, 3]
Example 2
Input: permutation_search_sort([5, -1, 5, 0])
Output: [-1, 0, 5, 5]
Example 3
Input: permutation_search_sort([])
Output: []
Example 4
Input: permutation_search_sort([1, 2, 3, 4])
Output: [1, 2, 3, 4]
Hints
Hint 1
Think about what a sorted list looks like in terms of adjacent pairs: every element must be less than or equal to its right neighbour.
Hint 2
Python's itertools.permutations generates every ordering of the positions, including repeated-looking ones when values are duplicated. That is fine, because you stop at the first ordering that passes the check.
Hint 3
Check the empty list and the single-element list: each has exactly one arrangement, which is already sorted. Convert the winning tuple back to a list before returning it.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Generate the arrangements of the input one by one. For each arrangement, scan adjacent pairs and check that no element is greater than its right neighbour. Return the first arrangement that passes.
Why it is correct
- Every arrangement produced is a rearrangement of the input, so the multiset of values is preserved, including duplicates.
- The search only stops on an arrangement that has no descending adjacent pair, which is exactly the definition of non-decreasing order.
- A sorted arrangement always exists, because sorting the input yields one. The search therefore always finds a result and terminates.
- Any two non-decreasing arrangements of the same multiset are identical as lists, so the answer is unique and matches what any correct sort returns.
- For an empty input,
permutationsyields a single empty tuple. It passes the check trivially, so the result is[]. The finalreturn []is never reached for valid input and is only a safeguard.
Complexity
- Time: there are up to
n!arrangements and each check costsO(n), so the worst case isO(n * n!). The best case, an input that is already sorted, finds a match on the first arrangement inO(n). - Space:
O(n)beyond the output, since arrangements are generated lazily.
Comparison
Any comparison-based sort needs Omega(n log n) comparisons in the worst case. Merge sort and heap sort achieve O(n log n). This approach is far above that bound because it makes no use of comparison results to narrow the search. A randomized variant that reshuffles and retests has an expected cost of about n * n! for distinct values but no finite worst-case bound. The deterministic enumeration always terminates within n! arrangements.
Reference solution
from itertools import permutations
from typing import List
def permutation_search_sort(values: List[int]) -> List[int]:
for candidate in permutations(values):
ok = True
for i in range(len(candidate) - 1):
if candidate[i] > candidate[i + 1]:
ok = False
break
if ok:
return list(candidate)
return []