From 7080c9958b58503a6e42ff24a4a7275228733d49 Mon Sep 17 00:00:00 2001 From: Akesh-28 Date: Sun, 1 Feb 2026 12:42:30 +0530 Subject: [PATCH] Refactor bubble sort for improved efficiency Refactor bubble sort algorithm to improve efficiency by reducing the range of each pass based on the last swap position. --- PythonCodes/bubbleSort.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/PythonCodes/bubbleSort.py b/PythonCodes/bubbleSort.py index adc48da..01a200e 100644 --- a/PythonCodes/bubbleSort.py +++ b/PythonCodes/bubbleSort.py @@ -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=" ") \ No newline at end of file + print("% d" % arr[i], end=" ")