Python 奇偶排序程式
在本文中,我們將學習如何解決以下給定的問題陳述。
問題陳述 − 給定一個數組,我們需要使用奇偶排序對它進行排序。
演算法
1. Check if value at index 0 is greater than value at last index,then swap them. 2. sort the initial 2/3rd of the array. 3. sort the last 2/3rd of the array. 4. sort the initial 2/3rd again to confirm.
現在讓我們觀察下面實現中的解決方案 −
示例
def stoogesort(arr, l, h): if l >= h: return # swap if arr[l]>arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t # more than 2 elements if h-l+1 > 2: t = (int)((h-l+1)/3) # sort first 2/3 elements stoogesort(arr, l, (h-t)) # sort last 2/3 elements stoogesort(arr, l+t, (h)) # sort first 2/3 elements again stoogesort(arr, l, (h-t)) # main arr = [1,4,2,3,6,5,8,7] n = len(arr) stoogesort(arr, 0, n-1) print ("Sorted sequence is:") for i in range(0, n): print(arr[i], end = " ")
輸出
Sorted sequence is: 1 2 3 4 5 6 7 8
所有變數均在區域性範圍內宣告,並且在上圖中可以看到它們的引用。
結論 −
在本文中,我們學習瞭如何編寫 Python 程式進行奇偶排序
廣告