Computer Hope

Software => Computer programming => Topic started by: samanthajade on September 25, 2020, 03:25:38 AM

Title: How to Solve this Problem using Recursive Bubble Sort Algorithm ?
Post by: samanthajade on September 25, 2020, 03:25:38 AM
Hey,

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

Code: [Select]
ArrayIndexOutOfBoundsException: 11
Code: [Select]
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;
}











Title: Re: How to Solve this Problem using Recursive Bubble Sort Algorithm ?
Post by: dphamnj on October 02, 2021, 10:14:18 AM
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)"

Code: [Select]
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 }
...