Python之双调排序

Python 专栏收录该内容
17 篇文章 2 订阅

(1)存在一个ak(1≤k≤n), 使得a1≥…≥ak≤…≤an成立；或者
(2)序列能够循环移位满足条件(1)

Batcher定理

Bitonic merge（双调合并）

Bitonic Sort（双调排序）

def compAndSwap(a, i, j, dire):
if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]):
a[i], a[j] = a[j], a[i]

def bitonicMerge(a, low, cnt, dire):
if cnt > 1:
k = int(cnt / 2)
for i in range(low, low + k):
compAndSwap(a, i, i + k, dire)
bitonicMerge(a, low, k, dire)
bitonicMerge(a, low + k, k, dire)

def bitonicSort(a, low, cnt, dire):
if cnt > 1:
k = int(cnt / 2)
bitonicSort(a, low, k, 1)
bitonicSort(a, low + k, k, 0)
bitonicMerge(a, low, cnt, dire)

def sort(a, N, up):
bitonicSort(a, 0, N, up)

if __name__ == "__main__":
# Driver code to test above
a = []

n = int(input().strip())
for i in range(n):
a.append(int(input().strip()))
up = 1

sort(a, n, up)
print("\n\nSorted array is")
for i in range(n):
print("%d" % a[i])

• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

04-27 261

12-17 670
08-11 1198
07-13 1150
02-27 1827
10-09 5122
08-04 56
08-28 26
12-25 563
03-26 365
01-09 351