Skip to content

Commit a0d5c9a

Browse files
Aruj-Sharmapoyea
authored andcommitted
Create BitonicSort.py (TheAlgorithms#386)
1 parent 1cbbd5f commit a0d5c9a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

sorts/BitonicSort.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Python program for Bitonic Sort. Note that this program
2+
# works only when size of input is a power of 2.
3+
4+
# The parameter dir indicates the sorting direction, ASCENDING
5+
# or DESCENDING; if (a[i] > a[j]) agrees with the direction,
6+
# then a[i] and a[j] are interchanged.*/
7+
def compAndSwap(a, i, j, dire):
8+
if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]):
9+
a[i], a[j] = a[j], a[i]
10+
11+
# It recursively sorts a bitonic sequence in ascending order,
12+
13+
14+
# if dir = 1, and in descending order otherwise (means dir=0).
15+
# The sequence to be sorted starts at index position low,
16+
# the parameter cnt is the number of elements to be sorted.
17+
def bitonicMerge(a, low, cnt, dire):
18+
if cnt > 1:
19+
k = int(cnt / 2)
20+
for i in range(low, low + k):
21+
compAndSwap(a, i, i + k, dire)
22+
bitonicMerge(a, low, k, dire)
23+
bitonicMerge(a, low + k, k, dire)
24+
25+
# This funcion first produces a bitonic sequence by recursively
26+
27+
28+
# sorting its two halves in opposite sorting orders, and then
29+
# calls bitonicMerge to make them in the same order
30+
def bitonicSort(a, low, cnt, dire):
31+
if cnt > 1:
32+
k = int(cnt / 2)
33+
bitonicSort(a, low, k, 1)
34+
bitonicSort(a, low + k, k, 0)
35+
bitonicMerge(a, low, cnt, dire)
36+
37+
# Caller of bitonicSort for sorting the entire array of length N
38+
39+
40+
# in ASCENDING order
41+
def sort(a, N, up):
42+
bitonicSort(a, 0, N, up)
43+
44+
45+
# Driver code to test above
46+
a = []
47+
48+
n = int(input())
49+
for i in range(n):
50+
a.append(int(input()))
51+
up = 1
52+
53+
sort(a, n, up)
54+
print("\n\nSorted array is")
55+
for i in range(n):
56+
print("%d" % a[i])

0 commit comments

Comments
 (0)