From 226c3a6be0ff842520e2afae37d3f47db70e8a4a Mon Sep 17 00:00:00 2001 From: Saloni Date: Thu, 11 Mar 2021 11:39:01 +0530 Subject: [PATCH] Adaptive Bubble Sort Implemented --- Python/sort/Bubble_Sort.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/Python/sort/Bubble_Sort.py b/Python/sort/Bubble_Sort.py index 009cb36d76..c17051f18a 100644 --- a/Python/sort/Bubble_Sort.py +++ b/Python/sort/Bubble_Sort.py @@ -1,7 +1,15 @@ +#Adaptive Bubble Sort (Loop runs only till the array is unsorted) + print("Enter the elements of the list to be sorted: ") -list = [int(x) for x in input().split(" ")] # Space seperated input -for i in range (len(list)-1): - for j in range (len(list)-1): - if (list[j] > list[j+1]): #Checking if current element greater than the next element - list[j], list[j+1] = list[j+1], list[j] #Swapping the elements -print("List after sorting: ", list); #Printing out the sorted list +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=" ")