-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbubblesort.py
66 lines (45 loc) · 1.49 KB
/
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'''
Bubble Sort
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are not in the intended order.
Time Complexity - O(n2)
'''
def bubbleSort(array):
# loop to access each array element
for i in range(len(array)):
# loop to compare array elements
for j in range(0, len(array) - i - 1):
# compare two adjacent elements
# change > to < to sort in descending order
if array[j] > array[j + 1]:
# swapping elements if elements
# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
list = [-2, 45, 0, 11, -9]
bubbleSort(list)
print(list) #[-9, -2, 0, 11, 45]
# Optimized
def bubbleSort(array):
# loop through each element of array
for i in range(len(array)):
# keep track of swapping
swapped = False
# loop to compare array elements
for j in range(0, len(array) - i - 1):
# compare two adjacent elements
# change > to < to sort in descending order
if array[j] > array[j + 1]:
# swapping occurs if elements
# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
swapped = True
# no swapping means the array is already sorted
# so no need for further comparison
if not swapped:
break
list = [-2, 45, 0, 11, -9]
bubbleSort(list)
print(list) #[-9, -2, 0, 11, 45]