Skip to content

Instantly share code, notes, and snippets.

@rblaine95
Last active October 22, 2021 10:10
Show Gist options
  • Save rblaine95/67db48b050b95a2ae51beedc6bd3d111 to your computer and use it in GitHub Desktop.
Save rblaine95/67db48b050b95a2ae51beedc6bd3d111 to your computer and use it in GitHub Desktop.
Permutation Sort - Given a list, generate every possible permutation of the list, then find the one that's sorted
#!/usr/bin/env python3
import itertools
from random import shuffle
def is_sorted(l):
for i in range(len(l)-1):
if l[i] > l[i+1]:
return False
return True
def permutation_sort(l):
if not is_sorted(l):
p = list(itertools.permutations(l))
print("there are", len(p), "permutations")
for x in range(len(p)-1):
if is_sorted(p[x]):
print(x, "is the one that's sorted")
return(p[x])
print("list is already sorted")
return l
def main():
max = 10
lst = [i for i in range(max)]
shuffle(lst)
print(permutation_sort(lst))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment