• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
Need help with Recursive Bubble Sort Algorithm
#1
Hey,

I am trying to implement bubble sort using recursion and have got a response

``ArrayIndexOutOfBoundsException: 11``

Unable to figure out where I went wrong..

``````public static int[] recBubSort(int []arr, int n){
if(n > arr.length-1){
return arr;
}

if(arr[n] > arr[n+1]){
swap(arr,n,n+1);
}
return recBubSort(arr,n+1);
}

public static void swap(int arr[], int minPos, int index) {
//System.out.println("SelectionSort SWAP...");
int temp = arr[minPos];
arr[minPos] = arr[index];
arr[index] = temp;
}``````

Tried Referring to these sources:
https://www.interviewbit.com/tutorial/bubble-sort/
http://www.techgeekbuzz.com/recursive-bubble-sort-in-c/
https://www.techiedelight.com/bubble-sor...recursive/

Would Appreciate your help in helping me debug this code.
#2
Hi pixielot, sa tingin ko nagkaka-arrayindexoutofbounds ka sa last index ng array mo. Kasi sa line 2 ng code mo nilagay mo is
``if(n > arr.length-1)``

So if meron kang array na:
``int[] arr = {5, 4, 8, 1, 3, 9};``

Tas pag nasa index 5 kana which is the last index, yung condition mo na n > arr.length, ay di mahihit. Therefore, tuloy tuloy sya tapos sa line 6 magkakaexception ka:
``if(arr[n] > arr[n+1])``

since arr[5 + 1] = wala na out of bounds na ng array.

Pwede mo ichange yung condition mo sa line 2 na:
``if(n > arr.length-2)``

Para di mahit yung exception. Though I don't think sorted na sya. Need mo pa ichange yung logic mo sa bubble sort.

Forum Jump:

 Users browsing this thread: 1 Guest(s)