Skip to content

Commit bb16f4a

Browse files
Merge pull request #558 from jyotish6699/feature/bubble-sort-order-selection
feat: add ascending and descending sorting support to Bubble Sort CLI
2 parents 7869768 + 5dba9ef commit bb16f4a

1 file changed

Lines changed: 71 additions & 19 deletions

File tree

math/Bubble-Sort/bubble_sort.py

Lines changed: 71 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,96 @@
1-
def bubble_sort(arr):
1+
print("🔄 Bubble Sort Interactive Tool 🔄")
2+
print("Sort numbers in Ascending or Descending order\n")
3+
4+
5+
def bubble_sort(arr, reverse=False):
26
"""
3-
Sorts a list in-place using the Bubble Sort algorithm.
7+
Sorts a list using the Bubble Sort algorithm.
48
Returns the sorted list.
59
"""
10+
11+
arr = arr.copy()
612
n = len(arr)
13+
714
for i in range(n):
815
swapped = False
16+
917
# Last i elements are already in place
10-
for j in range(0, n-i-1):
11-
# Swap if the element found is greater than the next element
12-
if arr[j] > arr[j+1]:
13-
arr[j],arr[j+1]=arr[j+1],arr[j]
18+
for j in range(0, n - i - 1):
19+
20+
# Ascending Order
21+
if not reverse and arr[j] > arr[j + 1]:
22+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
23+
swapped = True
24+
25+
# Descending Order
26+
elif reverse and arr[j] < arr[j + 1]:
27+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
1428
swapped = True
15-
# If no two elements were swapped by inner loop , then break
29+
30+
# If no swaps happened, list is already sorted
1631
if not swapped:
1732
break
33+
1834
return arr
1935

36+
2037
def test_bubble_sort():
21-
"""Background test cases to ensure logic accuracy before user input."""
38+
"""Background test cases to ensure logic accuracy."""
39+
40+
# Ascending Order Tests
2241
assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
2342
assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]
2443

44+
# Descending Order Tests
45+
assert bubble_sort([5, 1, 4, 2, 8], reverse=True) == [8, 5, 4, 2, 1]
46+
47+
# Edge Case Tests
48+
assert bubble_sort([]) == []
49+
assert bubble_sort([1]) == [1]
50+
assert bubble_sort([-1, -5, 3, 0]) == [-5, -1, 0, 3]
51+
52+
2553
if __name__ == "__main__":
26-
#Background testing execution
54+
55+
# Background testing execution
2756
test_bubble_sort()
2857

29-
# --- USER INTERACTION SECTION ---
3058
print("=== Bubble Sort Interactive Tool ===")
59+
3160
try:
32-
user_input = input("Enter numbers to sort seperated by spaces (e.g., 64 34 25) :")
61+
user_input = input(
62+
"➡️ Enter numbers to sort separated by spaces (e.g., 64 34 25): "
63+
)
64+
3365
if not user_input.strip():
34-
print("Error: Input cannot be empty!")
66+
print("❌ Error: Input cannot be empty!")
67+
3568
else:
36-
# Convert String Input into List of Integers
37-
arr=[int(x) for x in user_input.split()]
38-
print(f"Original list : {arr}")
69+
# Convert string input into list of integers
70+
arr = [int(x) for x in user_input.split()]
71+
72+
print("\nChoose sorting order:")
73+
print("1. Ascending")
74+
print("2. Descending")
75+
76+
order_choice = input("➡️ Enter your choice (1 or 2): ").strip()
77+
78+
if order_choice == "1":
79+
sorted_arr = bubble_sort(arr)
80+
81+
print(f"\n📊 Original list: {arr}")
82+
print(f"✅ Sorted list (Ascending): {sorted_arr}")
83+
84+
elif order_choice == "2":
85+
sorted_arr = bubble_sort(arr, reverse=True)
86+
87+
print(f"\n📊 Original list: {arr}")
88+
print(f"✅ Sorted list (Descending): {sorted_arr}")
89+
90+
else:
91+
print("❌ Invalid sorting choice! Please select 1 or 2.")
3992

40-
# Sort operation performed
41-
sorted_arr = bubble_sort(arr)
42-
print(f"Sorted list: {sorted_arr}")
4393
except ValueError:
44-
print("Error: Please enter valid integers only.")
94+
print("❌ Error: Please enter valid integers only.")
95+
96+
print("\n👋 Thank you for using Bubble Sort Tool!")

0 commit comments

Comments
 (0)