I have coded 2 bubblesort algorithms. One is without recursion, the other is with recursion. I am interested on knowing which of these two are more efficient and with and explain why.
Recursive bubbleSort:
private static int list[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
public int[] recursiveBubble(int[] args, int startIndex, int endIndex) {
if(startIndex > endIndex){
System.out.println("Recursive bubblesort:");
System.out.println(Arrays.toString(args));
return args;
}
if (startIndex == endIndex - 1) {
recursiveBubble(args, 0, endIndex - 1);
} else if (args[startIndex] > args[startIndex+1]) {
int currentNumber = args[startIndex];
args[startIndex] = args[startIndex + 1];
args[startIndex + 1] = currentNumber;
recursiveBubble(args, startIndex + 1, endIndex);
} else {
recursiveBubble(args, startIndex + 1, endIndex);
}
return args;
}
BubbleSort using loops:
public int[] bubblesort(int[] args) {
System.out.println("Normal BubbleSort:");
for (int j = 0; j < args.length; j++) {
for (int i = 0; i < args.length; i++) {
int currentNumber = args[i];
if (i + 1 < args.length) {
if (currentNumber > args[i + 1]) {
args[i] = args[i + 1];
args[i + 1] = currentNumber;
}
}
}
}
System.out.println(Arrays.toString(args));
return args;
}
I am not sure what you mean by which is better but bubble sort must inherently have a best and worst case performance time by nature of the way the algorithm works. Best case O(n) worst case O(n^2) see http://en.wikipedia.org/wiki/Bubble_sort . Iteration vs. recursion shouldn't make too much of a difference. I suppose recursion will take up more stack memory. Recursion tends to be harder to write and trace than iteration. Since there is no time benefit if both are actual bubble sort implementations I would stick to iteration.