From 4ca4f3d64abb9196447218384ae62916055e1171 Mon Sep 17 00:00:00 2001 From: Anuvrat Madaan Date: Fri, 9 Feb 2024 12:04:38 -0500 Subject: [PATCH] Adding a bubble sort algorithm for Python even thought python has a more efficient inbuilt sorting algorithm --- Algorithms/Python/Sorting/bubble_sort.py | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Algorithms/Python/Sorting/bubble_sort.py diff --git a/Algorithms/Python/Sorting/bubble_sort.py b/Algorithms/Python/Sorting/bubble_sort.py new file mode 100644 index 0000000..f31357a --- /dev/null +++ b/Algorithms/Python/Sorting/bubble_sort.py @@ -0,0 +1,38 @@ +""" + Bubble sort is a sorting algorithm in which every element is compared and swapped so that the last index is filled + with the correct element first +""" + + +def bubble_sort(arr, order=None): + """ + :param arr: array which needs to be sorted + :param order: Order of sorting, '1' for Descending, otherwise Ascending + :return: Sorted Array is returned + + Time Complexity: O(n^2) + Space Complexity: O(1) + """ + arr_len = len(arr) + for i in range(arr_len - 1): + for j in range(arr_len - 1 - i): + if order == '1': + if arr[j] < arr[j + 1]: + arr[j + 1], arr[j] = arr[j], arr[j + 1] + else: + if arr[j] > arr[j + 1]: + arr[j + 1], arr[j] = arr[j], arr[j + 1] + return arr + + +if __name__ == "__main__": + n = input("Enter space separated values of the array: ") + input_arr = list() + for ele in n.split(" "): + try: + input_arr.append(int(ele)) + except ValueError: + continue + print(f"Input Array: {input_arr}") + direction = input("Press 1 for Descending Order: ") + print(f"Sorted Array: {bubble_sort(input_arr, direction)}")