Skip to content

Commit 3f48669

Browse files
Create bubble.py
1 parent e8daffd commit 3f48669

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

sorting/bubble.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Python program for implementation of Bubble Sort
2+
3+
def bubbleSort(arr):
4+
n = len(arr)
5+
# optimize code, so if the array is already sorted, it doesn't need
6+
# to go through the entire process
7+
swapped = False
8+
# Traverse through all array elements
9+
for i in range(n-1):
10+
# range(n) also work but outer loop will
11+
# repeat one time more than needed.
12+
# Last i elements are already in place
13+
for j in range(0, n-i-1):
14+
15+
# traverse the array from 0 to n-i-1
16+
# Swap if the element found is greater
17+
# than the next element
18+
if arr[j] > arr[j + 1]:
19+
swapped = True
20+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
21+
22+
if not swapped:
23+
# if we haven't needed to make a single swap, we
24+
# can just exit the main loop.
25+
return
26+
27+
28+
# Driver code to test above
29+
arr = [64, 34, 25, 12, 22, 11, 90]
30+
31+
bubbleSort(arr)
32+
33+
print("Sorted array is:")
34+
for i in range(len(arr)):
35+
print("% d" % arr[i], end=" ")

0 commit comments

Comments
 (0)