Skip to content

Commit ecb752a

Browse files
author
Kalpak Take
authored
Create sort.py
Bubble sort algorithm
1 parent 938354f commit ecb752a

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

algorithms/analysis/sort.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
# Bubble Sort
5+
# Good sorting algorithm for
6+
# small data/array
7+
8+
# temporary parameter tells
9+
# function to sort a copy of
10+
# orignal array, and not the array itself
11+
12+
def sort_(arr, temporary = False):
13+
14+
# Making copy of array if temporary is true
15+
if temporary:
16+
ar = arr[:]
17+
else:
18+
ar = arr
19+
20+
# To blend every element in correct position
21+
# length of total array is required
22+
length = len(ar)
23+
24+
# After each iteration right-most
25+
# element is completed sorted
26+
while length > 0:
27+
28+
# So every next time we iterate only
29+
# through un-sorted elements
30+
for i in range(0, length - 1):
31+
32+
# Swapping greater elements to right
33+
# and smaller to left
34+
if ar[i] > ar[i+1]:
35+
tmp = ar[i]
36+
ar[i] = ar[i + 1]
37+
ar[i + 1] = tmp
38+
39+
# making sure loop breaks
40+
length = length - 1
41+
42+
# if temporary, then returning
43+
# copied arr's sorted form
44+
# cuz if not returned, then function
45+
# is literally of no use
46+
if temporary:
47+
return ar
48+
49+
# See proper explaination
50+
# at: https://www.geeksforgeeks.org/bubble-sort/
51+
# a good site!
52+
53+
54+
# Testing
55+
tests = [[9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [1312, 1110, 98, 76, 54, 32, 10], ] # Add your test cases
56+
for test in tests:
57+
c = sort_(test, True)
58+
if c == sorted(test):
59+
print("Orignal: {}".format(test))
60+
print("Sorted: {}".format(c))
61+
print("It worked!\n")
62+
else:
63+
print("Something went wrong!\n")
64+
65+
66+
# Seems our bubble sort works
67+
# however for small data or array!

0 commit comments

Comments
 (0)