Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a731ee4

Browse files
author
Amogh Singhal
authored
Update bubble_sort.py
1 parent 433721f commit a731ee4

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

‎bubble_sort.py‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,40 @@
11
# A simple implementation of bubble sort
22

33
def bubbleSort(arr):
4+
# travese the whole array
45
for i in range(len(arr)):
5-
for j in range(i+1, len(arr)):
6+
7+
# last i elements are already in place
8+
for j in range(0, len(arr)-i-1):
9+
10+
if arr[j] > arr[j+1]:
11+
arr[j], arr[j+1] = arr[j+1], arr[j]
12+
13+
return arr
14+
15+
# Approach 2: This algorithm will run for O(n^2) even if the array is
16+
# already sorted. For avoiding this, we can check if elements are swapped
17+
# in each pass. We will break the loop in case they are not
18+
19+
# Time Complexity: O(n^2) - Average or Worst Case; O(n) - Best case [Array is already sorted]
20+
21+
def bubbleSortOptimized(arr):
22+
for i in range(len(arr)):
23+
swapped = False
24+
25+
for j in range(0, len(arr)-i-1):
26+
627
if arr[i] > arr[j]:
728
arr[i], arr[j] = arr[j], arr[i]
29+
swapped = True
30+
31+
# if no elements are swapped, break the loop
32+
if swapped == False:
33+
break
834

935
return arr
1036

11-
arr = [2, 6, 1, 5, 3, 4]
12-
res = bubbleSort(arr)
13-
print(res)
37+
if __name__ = "__main__":
38+
arr = [2, 6, 1, 5, 3, 4]
39+
res = bubbleSort(arr)
40+
print(res)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /