2019-10-05 05:14:13 +00:00
|
|
|
# Python program for Bitonic Sort. Note that this program
|
|
|
|
# works only when size of input is a power of 2.
|
2019-02-11 09:53:49 +00:00
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
# The parameter dir indicates the sorting direction, ASCENDING
|
|
|
|
# or DESCENDING; if (a[i] > a[j]) agrees with the direction,
|
2020-05-22 06:10:11 +00:00
|
|
|
# then a[i] and a[j] are interchanged.
|
2019-02-11 09:53:49 +00:00
|
|
|
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]
|
|
|
|
|
|
|
|
# It recursively sorts a bitonic sequence in ascending order,
|
|
|
|
|
|
|
|
|
|
|
|
# if dir = 1, and in descending order otherwise (means dir=0).
|
2019-10-05 05:14:13 +00:00
|
|
|
# The sequence to be sorted starts at index position low,
|
|
|
|
# the parameter cnt is the number of elements to be sorted.
|
2020-03-04 12:40:28 +00:00
|
|
|
def bitonic_merge(a, low, cnt, dire):
|
2019-02-11 09:53:49 +00:00
|
|
|
if cnt > 1:
|
|
|
|
k = int(cnt / 2)
|
|
|
|
for i in range(low, low + k):
|
|
|
|
compAndSwap(a, i, i + k, dire)
|
2020-03-04 12:40:28 +00:00
|
|
|
bitonic_merge(a, low, k, dire)
|
|
|
|
bitonic_merge(a, low + k, k, dire)
|
2019-02-11 09:53:49 +00:00
|
|
|
|
2020-01-18 12:24:33 +00:00
|
|
|
# This function first produces a bitonic sequence by recursively
|
2019-02-11 09:53:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
# sorting its two halves in opposite sorting orders, and then
|
2020-03-04 12:40:28 +00:00
|
|
|
# calls bitonic_merge to make them in the same order
|
|
|
|
def bitonic_sort(a, low, cnt, dire):
|
2019-02-11 09:53:49 +00:00
|
|
|
if cnt > 1:
|
|
|
|
k = int(cnt / 2)
|
2020-03-04 12:40:28 +00:00
|
|
|
bitonic_sort(a, low, k, 1)
|
|
|
|
bitonic_sort(a, low + k, k, 0)
|
|
|
|
bitonic_merge(a, low, cnt, dire)
|
2019-02-11 09:53:49 +00:00
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
# Caller of bitonic_sort for sorting the entire array of length N
|
2019-02-11 09:53:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
# in ASCENDING order
|
|
|
|
def sort(a, N, up):
|
2020-03-04 12:40:28 +00:00
|
|
|
bitonic_sort(a, 0, N, up)
|
2019-02-11 09:53:49 +00:00
|
|
|
|
|
|
|
|
2019-07-08 15:27:51 +00:00
|
|
|
if __name__ == "__main__":
|
2020-03-04 12:40:28 +00:00
|
|
|
|
2019-07-08 15:27:51 +00:00
|
|
|
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])
|