Skip to content

Commit

Permalink
Added documentation and driver code
Browse files Browse the repository at this point in the history
  • Loading branch information
SaloniSwagata committed Mar 15, 2021
1 parent 226c3a6 commit e23a1cc
Showing 1 changed file with 27 additions and 14 deletions.
41 changes: 27 additions & 14 deletions Python/sort/Bubble_Sort.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
#Adaptive Bubble Sort (Loop runs only till the array is unsorted)
'''
bubble_sort() function uses an iterative approach sort the array in increasing
order passed as an argument. It compares adjacent elements and swappes them if
there is any larger element before the smaller element. After the first pass,
the most heaviest element shifts to the last position.
The flag is used to check if any swapping is performed or not. If no swapping is
done, the loop breaks as the array is already sorted.
Time Complexity: O(n^2)
Space Complexity: O(1)
Return Type: No return type as lists are mutable
'''
def bubble_sort(Array):
for i in range (len(Array)-1):
flag = True
for j in range (len(Array)-1):
if (Array[j] > Array[j+1]):
flag = False
Array[j], Array[j+1] = Array[j+1], Array[j]
if flag:
break

print("Enter the elements of the list to be sorted: ")
Array = [int(x) for x in input().split(" ")] # Space seperated input
for i in range (len(Array)-1):
flag = True # Flag for checking if the array is sorted or not
for j in range (len(Array)-1):
if (Array[j] > Array[j+1]): #Checking if current element greater than the next element
flag = False #The array is still unsorted
Array[j], Array[j+1] = Array[j+1], Array[j] #Swapping the elements
if flag: #Checking if the array is already sorted
break
print("List after sorting: ")#Printing out the sorted list
for i in Array:
print(i,end=" ")
if __name__=="__main__":
print("Enter the elements of the list to be sorted: ")
Array = [int(x) for x in input().split(" ")]
bubble_sort(Array)
print("List after sorting: ")
for i in Array:
print(i,end=" ")

0 comments on commit e23a1cc

Please sign in to comment.