用于奇偶排序/砖排序的Python程序
这基本上是冒泡排序的一种变体。该算法分为两个阶段——奇数阶段和偶数阶段。该算法一直运行直到数组元素被排序并且在每次迭代中出现两个阶段——奇数阶段和偶数阶段。
在奇数阶段,我们对奇数索引元素执行冒泡排序,在偶数阶段,我们对偶数索引元素执行冒泡排序。
# Python Program to implement
# Odd-Even / Brick Sort
def oddEvenSort(arr, n):
# Initially array is unsorted
isSorted = 0
while isSorted == 0:
isSorted = 1
temp = 0
for i in range(1, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
isSorted = 0
for i in range(0, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
isSorted = 0
return
arr = [34, 2, 10, -9]
n = len(arr)
oddEvenSort(arr, n);
for i in range(0, n):
print(arr[i], end =" ")
# Code Contribute by Mohit Gupta_OMG <(0_o)>
输出 :
-9 2 10 34
有关详细信息,请参阅有关奇偶排序/砖排序的完整文章!