How to Solve this Problem using Recursive Bubble Sort Algorithm ?

Started by samanthajade, September 25, 2020, 03:25:38 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

samanthajade

Hey,

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

ArrayIndexOutOfBoundsException: 11

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













dphamnj

Because the if statement in line 6 is using an invalid index of n+1 when n=arr.length-1.  May be change the if statement in line 2 to "if (n >= arr.length-1)"


1   public static int[] recBubSort(int []arr, int n){
2   if(n > arr.length-1){
3   return arr;
4   }
5   
6   if(arr[n] > arr[n+1]){
7   swap(arr,n,n+1);
8   }
9   return recBubSort(arr,n+1);
10 }
...