From 3fc8c07feeb69004e8988a33df1666cd8811b7ad Mon Sep 17 00:00:00 2001 From: Dilshad Alam <134841643+Dilshad-mohammad@users.noreply.github.com> Date: Tue, 29 Oct 2024 18:02:36 +0530 Subject: [PATCH] Created bubble sort --- bubble sort | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 bubble sort diff --git a/bubble sort b/bubble sort new file mode 100644 index 00000000..99e3c9c7 --- /dev/null +++ b/bubble sort @@ -0,0 +1,20 @@ +def bubble_sort_swaps(arr, ascending=True): + n = len(arr) + swaps = 0 + for i in range(n): + for j in range(0, n-i-1): + if (ascending and arr[j] > arr[j+1]) or (not ascending and arr[j] < arr[j+1]): + arr[j], arr[j+1] = arr[j+1], arr[j] # Swap + swaps += 1 + return swaps + +# Input reading +N = int(input()) # Number of elements +arr = list(map(int, input().split())) # Array elements + +# Count swaps for both ascending and descending order +ascending_swaps = bubble_sort_swaps(arr.copy(), ascending=True) +descending_swaps = bubble_sort_swaps(arr.copy(), ascending=False) + +# Output the minimum number of swaps +print(min(ascending_swaps, descending_swaps))