Bubble Sort in Python
Overview
Bubble sort algorithm costs O(n*n)
time complexity.
Here is an implementation in Python – short and sweet.
If you really want to sort you can use python std library or even
other libraries using better algorithms. This is just to
illustrate how to implement a simple algorithm in Python.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#!/bin/python3 def bubble_sort(mylist): n = len(mylist) for i in range(n): # The last i elements are already sorted. for j in range(0, n - i - 1): if mylist[j] > mylist[j + 1]: # Swap it. Heavier elements keep moving to last. mylist[j], mylist[j+1] = mylist[j+1], mylist[j] return mylist if __name__ == '__main__': print("Enter numbers separated by space: ") numbers = [ int(i) for i in input().rstrip().split() ] # We make a copy with list(numbers) to keep original untouched. print("Bubble Sort Result: ", bubble_sort(list(numbers))) print("Note: Original list:", numbers) numbers.sort() print("Note: Python built-in sort result: ", numbers) numbers.sort(reverse=True) print("Note: Python built-in sort (reverse) result: ", numbers) # Example Run: # $ python3 -i sortb.py <<< "6 1 8 3 0 5 2 9 7" # Enter numbers separated by space: # Bubble Sort Result: [0, 1, 2, 3, 5, 6, 7, 8, 9] # Note: Original list: [6, 1, 8, 3, 0, 5, 2, 9, 7] # Note: Python built-in sort result: [0, 1, 2, 3, 5, 6, 7, 8, 9] # Note: Python built-in sort (reverse) result: [9, 8, 7, 6, 5, 3, 2, 1, 0] |