forked from noisebridge/PythonClass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubblesort.py
69 lines (51 loc) · 2.07 KB
/
bubblesort.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
''' Docstring: Where you put your notes
Lorem ipsum...
Lorem ipsum...
'''
def bubble_sort(unsorted_list):
''' This is a short description of the function
You can have more info below, this turns into output for the
help() builtin function
'''
# if we were doing from the right to the left
# i = len(unsorted_list) - 1
# we need to have an index!!
# start at the leftmost pair
i = 0
# run at least once
# python does not have: do... while
has_been_swapped = True
while has_been_swapped:
# has a swap occurred yet in this loop?
has_been_swapped = False
# "get to the end" - if i = len(unsorted_list)-1
# if we "get to the end" start over
while i < (len(unsorted_list) - 1):
# atomic action - everything comes down to the comparison
# grab two items and compare them
if unsorted_list[i] > unsorted_list[i+1]:
has_been_swapped = True
print(unsorted_list[i], unsorted_list[i+1])
# "change the order" - swap the left-side and the right-side values
# "change the order" if the right-side number is smaller than the left-side
# more pythonic, but less readable? depends on the reader
# unsorted_list[i], unsorted_list[i+1] = unsorted_list[i+1], unsorted_list[i]
_temp = unsorted_list[i]
unsorted_list[i] = unsorted_list[i+1]
unsorted_list[i+1] = _temp
# move on to the next pair - move to the right one spot
i += 1
# "start over" - go back to the top.... set the index to zero again
i = 0
# what data type comes out? a list of numbers
return unsorted_list
if __name__ == "__main__":
import random # used shuffle method only
# what data type goes in? a list of numbers
my_list = [3,2,1]
print(bubble_sort(my_list))
# lets do a bigger list
another_list = range(100)
random.shuffle(another_list)
print(another_list)
print(bubble_sort(another_list))