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;
}