MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / bubble_sort

Function bubble_sort

sorts/bubble_sort.py:4–32  ·  view source on GitHub ↗

Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> bubble_

(collection)

Source from the content-addressed store, hash-verified

2
3
4def 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 >>> bubble_sort([-23,0,6,-4,34])
22 [-23,-4,0,6,34]
23 """
24 length = len(collection)
25 for i in range(length-1):
26 swapped = False
27 for j in range(length-1-i):
28 if collection[j] > collection[j+1]:
29 swapped = True
30 collection[j], collection[j+1] = collection[j+1], collection[j]
31 if not swapped: break # Stop iteration if the collection is sorted.
32 return collection
33
34
35if __name__ == '__main__':

Callers 1

bubble_sort.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected