Skip to content

Commit 30cd255

Browse files
Merge pull request #6998 from sulaemanahmed/patch-8
Update Bubble_sort.py
2 parents 21d008b + 206ba7b commit 30cd255

1 file changed

Lines changed: 33 additions & 29 deletions

File tree

Add Code Here/All_Sorting/Bubble_sort.py

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,39 @@
1-
# Python program for implementation of Bubble Sort
2-
31
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):
2+
n = len(arr)
3+
# optimize code, so if the array is already sorted, it doesn't need
4+
# to go through the entire process
5+
swapped = False
6+
# Traverse through all array elements
7+
for i in range(n - 1):
8+
# range(n) also works but the outer loop will
9+
# repeat one time more than needed.
10+
# Last i elements are already in place
11+
for j in range(0, n - i - 1):
12+
# traverse the array from 0 to n-i-1
13+
# Swap if the element found is greater
14+
# than the next element
15+
if arr[j] > arr[j + 1]:
16+
swapped = True
17+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
18+
19+
if not swapped:
20+
# if we haven't needed to make a single swap, we
21+
# can just exit the main loop.
22+
return
1423

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
24+
def main():
25+
n = int(input("Enter the number of elements: "))
26+
arr = []
27+
for i in range(n):
28+
element = int(input(f"Enter element {i+1}: "))
29+
arr.append(element)
2630

31+
bubbleSort(arr)
2732

28-
# Driver code to test above
29-
arr = [64, 34, 25, 12, 22, 11, 90]
33+
print("Sorted array is:")
34+
for i in range(len(arr)):
35+
print("%d" % arr[i], end=" ")
3036

31-
bubbleSort(arr)
37+
if __name__ == "__main__":
38+
main()
3239

33-
print("Sorted array is:")
34-
for i in range(len(arr)):
35-
print("% d" % arr[i], end=" ")

0 commit comments

Comments
 (0)