|
1 | 1 | from __future__ import print_function
|
2 | 2 |
|
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 | + |
16 | 32 | if __name__ == '__main__':
|
17 | 33 | try:
|
18 | 34 | raw_input # Python 2
|
|
0 commit comments