'BubbleSort with recursion in Python3 - Returning "None"
I created a small function to do BubbleSort (just learning how to code) in Python 3 and I can't find the issue.
Here is the code. It's returning "None" for some reason. Could someone please take a look? Thank you!
arr = [1,5,2,7,3]
def bubbleSort(array):
count = 0
#print("array is currently",array)
for idx in range(len(array)-1):
if array[idx] > array[idx + 1]:
array[idx],array[idx + 1] = array[idx + 1],array[idx]
count += 1
#print("swaped and count is currently",count)
#print("array is currently",array)
if count == 0:
#print("Count is zero")
#print("array is currently",array)
return array
else:
#print("Count is not zero")
bubbleSort(array)
print(bubbleSort(arr))
Solution 1:[1]
I really liked @user3065757 approach! Anyway, my code is
def rec_bubble_sort(myList):
flag = 0
for i in range(len(myList)-1):
if myList[i] > myList[i+1]:
myList[i], myList[i+1] = myList[i+1], myList[i]
flag = 1
if flag:
return rec_bubble_sort(myList[0:len(myList)-1])+myList[len(myList)-1:]
else:
return myList
myList = [2, 6, 4, 0, 5, 7, 2, 4, 1]
print(rec_bubble_sort(myList))
My code is similar to @RohithS98 but I have used
return rec_bubble_sort(myList[0:len(myList)-1])+myList[len(myList)-1:]
The reason behind this is that when the function is called, it would not traverse the entire list.
Solution 2:[2]
Bubble sort using recursion without using any loop,
def bubble_sort_recur(a, i, j, n):
if j == n:
i = i+1
j = 0
if i == n:
return
if a[i] > a[j]:
temp = a[j]
a[j] = a[i]
a[i] = temp
bubble_sort_recur(a, i, j+1, n);
else:
bubble_sort_recur(a, i, j + 1, n);
return a
a = [1, 12, 3, 4]
a = bubble_sort_recur(a, 0, 0, len(a))
print(a)
Solution 3:[3]
A simplest solution with less line of code:
def bubblesort(l,n):
for i in range(len(l)-2):
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
if n>1:
bubblesort(l,n-1)
l = [6,2,9,11,9,3,7,12]
n=len(l)
bubblesort(l,n)
print(l)
Solution 4:[4]
public class RecursionBubbleSort {
public static void main(String[] args) {
int[] nums = {4, 3, 2, 1};
int[] sorted = bubbleSort(nums, 1, nums.length);
for(int i: sorted){
System.out.print(i + " ");
}
}
public static int[] bubbleSort(int[] nums, int start, int end){
if(start >= end) return nums;
nums = innerSort(nums, start, end);
return bubbleSort(nums, start, end-1);
}
public static int[] innerSort(int[] nums, int start, int size){
if(start >= size) return nums;
if(nums[start-1] > nums[start]){
int temp = nums[start];
nums[start] = nums[start-1];
nums[start-1] = temp;
}
return innerSort(nums, start+1, size);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rish_hyun |
| Solution 2 | Rakesh Chaudhari |
| Solution 3 | user3065757 |
| Solution 4 | Flair |
