Skip to content

Commit 76a1d9d

Browse files
authored
Merge pull request keon#89 from ss18/sort/bubble_sort
Bubble sort
2 parents 23aedf8 + 866d583 commit 76a1d9d

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,9 @@ Minimal and clean example implementations of data structures and algorithms in P
129129
- [set](set)
130130
- [randomized_set](set/randomized_set.py)
131131
- [sort](sort)
132+
- [bubble_sort](sort/bubble_sort.py)
133+
- [counting_sort](sort/counting_sort.py)
134+
- [heap_sort](sort/heap_sort.py)
132135
- [insertion_sort](sort/insertion_sort.py)
133136
- [meeting_rooms](sort/meeting_rooms.py)
134137
- [merge_sort](sort/merge_sort.py)
@@ -137,7 +140,6 @@ Minimal and clean example implementations of data structures and algorithms in P
137140
- [sort_colors](sort/sort_colors.py)
138141
- [topsort](sort/topsort.py)
139142
- [wiggle_sort](sort/wiggle_sort.py)
140-
- [counting_sort](sort/counting_sort.py)
141143
- [stack](stack)
142144
- [longest_abs_path](stack/longest_abs_path.py)
143145
- [simplify_path](stack/simplify_path.py)

sort/bubble_sort.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
3+
https://en.wikipedia.org/wiki/Bubble_sort
4+
5+
Complexity: O(N^2)
6+
7+
"""
8+
9+
10+
def bubble_sort(arr):
11+
12+
def swap(i, j):
13+
arr[i], arr[j] = arr[j], arr[i]
14+
15+
n = len(arr)
16+
swapped = True
17+
while swapped:
18+
swapped = False
19+
for i in range(1, n):
20+
if arr[i - 1] > arr[i]:
21+
swap(i - 1, i)
22+
swapped = True
23+
24+
array = [1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100,
25+
4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]
26+
print(array)
27+
bubble_sort(array)
28+
print(array)

0 commit comments

Comments
 (0)