📜  用于 BogoSort 或置换排序的Python程序

📅  最后修改于: 2022-05-13 01:56:56.433000             🧑  作者: Mango

用于 BogoSort 或置换排序的Python程序

BogoSort 也称为置换排序、愚蠢排序、慢排序、猎枪排序或猴子排序,是一种基于生成和测试范式的特别无效的算法。该算法连续生成其输入的排列,直到找到已排序的排列。(Wiki)
例如,如果使用 bogosort 对一副纸牌进行排序,它将包括检查纸牌是否有序,如果不是,则将纸牌扔到空中,随机捡起纸牌,然后重复该过程直到甲板被分类。

伪代码:

while not Sorted(list) do
    shuffle (list)
done

Python3
# Python program for implementation of Bogo Sort
import random
 
# Sorts array a[0..n-1] using Bogo sort
def bogoSort(a):
    n = len(a)
    while (is_sorted(a)== False):
        shuffle(a)
 
# To check if array is sorted or not
def is_sorted(a):
    n = len(a)
    for i in range(0, n-1):
        if (a[i] > a[i+1] ):
            return False
    return True
 
# To generate permutation of the array
def shuffle(a):
    n = len(a)
    for i in range (0,n):
        r = random.randint(0,n-1)
        a[i], a[r] = a[r], a[i]
 
# Driver code to test above
a = [3, 2, 4, 1, 0, 5]
bogoSort(a)
print("Sorted array :")
for i in range(len(a)):
    print ("%d" %a[i]),


输出:

Sorted array :
0
1
2
3
4
5

有关详细信息,请参阅有关 BogoSort 或 Permutation Sort 的完整文章!