用於 BogoSort 或置換排序的 Python 程式
在本文中,我們將瞭解如何解決以下問題陳述。
問題陳述 − 我們得到一個數組,我們需要使用置換排序的概念對它進行排序。
BogoSort 也稱為置換排序,它基於生成和測試範例。
現在,讓我們瞭解一下以下實現中的解決方案−
示例
# random module
import random
# Sort
def bogoSort(a):
n = len(a)
while (is_sorted(a)== False):
shuffle(a)
# check
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
return False
return True
# permutation
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]
# main
a = [1,5,3,4,8,6,3,4,5]
bogoSort(a)
print("Sorted array :")
for i in range(len(a)):
print (a[i],end=" ")輸出
Sorted array is : 1 3 3 4 4 5 5 6 8

所有變數都在區域性範圍內宣告,並且其引用在上圖中可見。
結論
在本文中,我們學習瞭如何編寫用於 BogoSort 或置換排序的 Python 程式
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP