|
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 |
| - |
13 |
| -from __future__ import print_function |
14 |
| - |
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 |
| - |
44 |
| -if __name__ == '__main__': |
45 |
| - try: |
46 |
| - raw_input # Python 2 |
47 |
| - except NameError: |
48 |
| - raw_input = input # Python 3 |
49 |
| - |
50 |
| - user_input = raw_input('Enter numbers separated by a comma:\n').strip() |
51 |
| - unsorted = [int(item) for item in user_input.split(',')] |
52 |
| - print(bubble_sort(unsorted)) |
| 1 | +def bubbleSort(arr): |
| 2 | + n = len(arr) |
| 3 | + |
| 4 | + # Traverse through all array elements |
| 5 | + for i in range(n): |
| 6 | + |
| 7 | + # Last i elements are already in place |
| 8 | + for j in range(0, n-i-1): |
| 9 | + |
| 10 | + # traverse the array from 0 to n-i-1 |
| 11 | + # Swap if the element found is greater |
| 12 | + # than the next element |
| 13 | + if arr[j] > arr[j+1] : |
| 14 | + arr[j], arr[j+1] = arr[j+1], arr[j] |
| 15 | + |
| 16 | +# Driver code to test above |
| 17 | +arr = [64, 34, 25, 12, 22, 11, 90] |
| 18 | + |
| 19 | +bubbleSort(arr) |
| 20 | + |
| 21 | +print ("Sorted array is:") |
| 22 | +for i in range(len(arr)): |
| 23 | + print ("%d" %arr[i]), |
0 commit comments