If you determine all of the permutations and then sort it, your time complexity is a little off. Say you have an n
character long string. Based on a couple resources found from a quick search (complexity of recursive string permutation function, Time complexity of this code to list all permutations?), the time complexity for determining the permutations is Theta(n*n!)
This will generate n!
different permutations. Now, to sort these permutations, it will take Theta(n! lg n!)
, for a total time complexity of:
Theta(n*n!) + Theta(n! lg n!)
You can remove the need to do that expensive sort at the end by constructing an algorithm that generates the permutations, preserving the sorted order.
I am imagining some recursive algorithm that takes each successive character as the initial character of the permutation and then determines the permutation of the rest of the string (which will be sorted as well).
Something like (sorry for the partially pseudo-code, partially Python):
def sorted_permute(str):
if len(str) == 1:
return [str]
all_permutations = []
for pos in len(str):
next_str = str[:pos] + str[pos+1:]
permutations = sorted_permute(next_str)
permutations.prepend_to_all(str[pos]) # This could be expensive
all_permutations.append(permutations)
return all_permutations
***** EDIT *****
If you do not want to store the permutations and you really just care about printing the permutations, you can do something like the following:
def sorted_permute(str, head):
if len(str) == 0:
print(head)
for pos in len(str):
next_str = str[:pos] + str[pos+1:]
new_head = head + str[pos]
sorted_permute(next_str, new_head)
O(n!)
, unless you can somehow modify the permutation-generating algorithm to reject non sorted stings along the way without doing additional work. – Tim Biegeleisen