Skip to content

Commit f0d5bc6

Browse files
committed
Merge branch 'improved_sorting_algo' of git://github.com/YasirChoudhary/Python
2 parents 3bab59a + 9561259 commit f0d5bc6

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

sorts/bubble_sort.py

+29-13
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,34 @@
11
from __future__ import print_function
22

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-
3+
4+
def bubble_sort(collection):
5+
"""Pure implementation of bubble sort algorithm in Python
6+
7+
:param collection: some mutable ordered collection with heterogeneous
8+
comparable items inside
9+
:return: the same collection ordered by ascending
10+
11+
Examples:
12+
>>> bubble_sort([0, 5, 3, 2, 2])
13+
[0, 2, 2, 3, 5]
14+
15+
>>> bubble_sort([])
16+
[]
17+
18+
>>> bubble_sort([-2, -5, -45])
19+
[-45, -5, -2]
20+
"""
21+
length = len(collection)
22+
for i in range(length-1):
23+
swapped = False
24+
for j in range(length-1-i):
25+
if collection[j] > collection[j+1]:
26+
swapped = True
27+
collection[j], collection[j+1] = collection[j+1], collection[j]
28+
if not swapped: break # Stop iteration if the collection is sorted.
29+
return collection
30+
31+
1632
if __name__ == '__main__':
1733
try:
1834
raw_input # Python 2

sorts/selection_sort.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def selection_sort(collection):
3131
"""
3232

3333
length = len(collection)
34-
for i in range(length):
34+
for i in range(length - 1):
3535
least = i
3636
for k in range(i + 1, length):
3737
if collection[k] < collection[least]:

0 commit comments

Comments
 (0)