Advertisement
182days

Bubble Sort Example

May 10th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. #bubble sort example, prints each line of the list as it becomes sorted.
  2. import time
  3. my_list = [3, 5, 78, 1, 15, 25, 99, 8] #list requiring sorting
  4. print("original list was ",(my_list)) #print unsorted list
  5. def bubble(unsorted):
  6.     length = len(unsorted) - 1
  7.     sorted = False
  8.  
  9.     while not sorted:
  10.         sorted = True
  11.         for i in range(length):
  12.             if unsorted[i] > unsorted[i+1]: #if first item is bigger than second then it needs sorting
  13.                 sorted = False
  14.                 unsorted[i], unsorted[i+1] = unsorted[i+1], unsorted[i] #move the first item after the second item & repeat
  15.                 print (my_list)
  16.                 time.sleep(1)
  17.  
  18. bubble(my_list)
  19. print("sorted list is now ",(my_list)) #print the final sorted list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement