Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: How to Solve this Problem using Recursive Bubble Sort Algorithm ?  (Read 92722 times)

0 Members and 1 Guest are viewing this topic.

samanthajade

    Topic Starter


    Newbie

    • Experience: Familiar
    • OS: Windows 10
    How to Solve this Problem using Recursive Bubble Sort Algorithm ?
    « 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;
    }












    dphamnj



      Starter

      Thanked: 2
      • Experience: Experienced
      • OS: Linux variant
      Re: How to Solve this Problem using Recursive Bubble Sort Algorithm ?
      « Reply #1 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 }
      ...