Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions PythonCodes/bubbleSort.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
def bubbleSort(arr):
n = len(arr)
swapped = False
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
swapped = True
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if not swapped:
return
n = len(arr)
while n>1: # Repeat passes until the unsorted part has more than one element

new_n=0 # Stores the index of the last swap in this pass
for i in range(1,n):
if(arr[i-1]>arr[i]): # Check if adjacent elements are in wrong order
arr[i],arr[i-1]=arr[i-1],arr[i] #swap the elements
new_n=i # Update last swapped position
n=new_n # Reduce the range for the next pass
#example
arr = [64, 34, 25, 12, 22, 11, 90]
print("Before sorting ",arr )
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("% d" % arr[i], end=" ")
print("% d" % arr[i], end=" ")