forked from OmkarPathak/pygorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.py
More file actions
63 lines (51 loc) · 1.42 KB
/
bubble_sort.py
File metadata and controls
63 lines (51 loc) · 1.42 KB
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
"""
Author: OMKAR PATHAK
Contributors: Mohamed Kiouaz
Created On: 31st July 2017
Best O(n); Average O(n*(n-1)/4); Worst O(n^2)
"""
import inspect
def sort(_list):
"""
Bubble Sorting algorithm
:param _list: list of values to sort
:return: sorted values
"""
for i in range(len(_list)):
for j in range(len(_list) - 1, i, -1):
if _list[j] < _list[j - 1]:
_list[j], _list[j - 1] = _list[j - 1], _list[j]
return _list
def improved_sort(_list):
"""
Improved Bubble Sorting algorithm
:param _list: list of values to sort
:return: sorted values
"""
for i in range(len(_list)):
stop = True
for j in range(len(_list) - 1, i, -1):
if _list[j] < _list[j - 1]:
stop = False
_list[j], _list[j - 1] = _list[j - 1], _list[j]
if stop:
return _list
return _list
# TODO: Are these necessary?
def time_complexities():
"""
Return information on functions
time complexity
:return: string
"""
return "Best Case: O(n), " \
"Average Case: O(n ^ 2), " \
"Worst Case: O(n ^ 2).\n\n" \
"For Improved Bubble Sort:\nBest Case: O(n); Average Case: O(n * (n - 1) / 4); Worst Case: O(n ^ 2)"
def get_code():
"""
easily retrieve the source code
of the sort function
:return: source code
"""
return inspect.getsource(sort)