Python: Sort unsorted numbers using Recursive Bubble Sort
30. Recursive Bubble Sort
Write a Python program to sort unsorted numbers using Recursive Bubble Sort.
Sample Solution:
Python Code:
#Ref.https://bit.ly/3oneU2l
def bubble_sort(list_data: list, length: int = 0) -> list:
length = length or len(list_data)
swapped = False
for i in range(length - 1):
if list_data[i] > list_data[i + 1]:
list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i]
swapped = True
return list_data if not swapped else bubble_sort(list_data, length - 1)
nums = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Insertion Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Bubble Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Bubble Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
nums = ['z','a','y','b','x','c']
print("\nOriginal list:")
print(nums)
print("After applying Recursive Bubble Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
Sample Output:
Original list: [4, 3, 5, 1, 2] After applying Recursive Insertion Sort the said list becomes: [1, 2, 3, 4, 5] Original list: [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] After applying Recursive Bubble Sort the said list becomes: [-18, -4, 0, 3, 5, 5, 7, 9, 10, 46, 92, 178] Original list: [1.1, 1, 0, -1, -1.1, 0.1] After applying Recursive Bubble Sort the said list becomes: [-1.1, -1, 0, 0.1, 1, 1.1] Original list: ['z', 'a', 'y', 'b', 'x', 'c'] After applying Recursive Bubble Sort the said list becomes: ['a', 'b', 'c', 'x', 'y', 'z']
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to implement bubble sort recursively and print the list after each full pass.
- Write a Python script to recursively bubble sort a list and count the number of swaps performed.
- Write a Python program to use recursive bubble sort to sort a list of strings and then verify the sorted order.
- Write a Python function to implement recursive bubble sort and compare its performance with the iterative version on small datasets.
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to sort a given collection of numbers and its length in ascending order using Recursive Insertion Sort.
Next: Write a Python program to sort unsorted numbers using Random Pivot Quick Sort. Picks the random index as the pivot.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.