Skip to content

Commit 16aea14

Browse files
authored
Merge pull request TheAlgorithms#420 from prateekyo/master
Update bubble_sort.py
2 parents 4cff20b + f9f5d40 commit 16aea14

File tree

1 file changed

+15
-44
lines changed

1 file changed

+15
-44
lines changed

sorts/bubble_sort.py

+15-44
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,23 @@
1-
"""
2-
This is pure python implementation of bubble sort algorithm
3-
4-
For doctests run following command:
5-
python -m doctest -v bubble_sort.py
6-
or
7-
python3 -m doctest -v bubble_sort.py
8-
9-
For manual testing run:
10-
python bubble_sort.py
11-
"""
12-
131
from __future__ import print_function
142

15-
16-
def bubble_sort(collection):
17-
"""Pure implementation of bubble sort algorithm in Python
18-
19-
:param collection: some mutable ordered collection with heterogeneous
20-
comparable items inside
21-
:return: the same collection ordered by ascending
22-
23-
Examples:
24-
>>> bubble_sort([0, 5, 3, 2, 2])
25-
[0, 2, 2, 3, 5]
26-
27-
>>> bubble_sort([])
28-
[]
29-
30-
>>> bubble_sort([-2, -5, -45])
31-
[-45, -5, -2]
32-
"""
33-
length = len(collection)
34-
for i in range(length):
35-
swapped = False
36-
for j in range(length-1):
37-
if collection[j] > collection[j+1]:
38-
swapped = True
39-
collection[j], collection[j+1] = collection[j+1], collection[j]
40-
if not swapped: break # Stop iteration if the collection is sorted.
41-
return collection
42-
43-
3+
def bubble_sort(arr):
4+
n = len(arr)
5+
# Traverse through all array elements
6+
for i in range(n):
7+
# Last i elements are already in place
8+
for j in range(0, n-i-1):
9+
# traverse the array from 0 to n-i-1
10+
# Swap if the element found is greater
11+
# than the next element
12+
if arr[j] > arr[j+1] :
13+
arr[j], arr[j+1] = arr[j+1], arr[j]
14+
return arr
15+
4416
if __name__ == '__main__':
4517
try:
4618
raw_input # Python 2
4719
except NameError:
4820
raw_input = input # Python 3
49-
50-
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
21+
user_input = raw_input('Enter numbers separated by a comma:').strip()
5122
unsorted = [int(item) for item in user_input.split(',')]
52-
print(bubble_sort(unsorted))
23+
print(*bubble_sort(unsorted), sep=',')

0 commit comments

Comments
 (0)