-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbubblesort.py
31 lines (23 loc) · 939 Bytes
/
bubblesort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#BUBBLESORT Algorithm
#Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if they are not in the intended order.
#The order can be ascending or descending.
#pseudocode
#bubbleSort(array)
# for i <- 1 to indexOfLastUnsortedElement-1
# if leftElement > rightElement
# swap leftElement and rightElement
#end bubbleSort
#Algorithm
def bubbleSort(array):
# run loops two times: one for walking throught the array
# and the other for comparison
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
# To sort in descending order, change > to < in this line.
if array[j] > array[j + 1]:
# swap if greater is at the rear position
(array[j], array[j + 1]) = (array[j + 1], array[j])
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Asc ending Order:')
print(data)