Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Algorithms/Python/Sorting/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -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):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

introduce an optimization to stop sorting if no swaps are made in a pass, as the array is already sorted

"""
: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(" "):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add input validation to ensure that the list contains comparable elements before sorting.

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)}")