Web Analytics Made Easy -
StatCounter Need help with this Recursive Bubble Sort Exception? - CodingForum

Announcement

Collapse
No announcement yet.

Need help with this Recursive Bubble Sort Exception?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Need help with this Recursive Bubble Sort Exception?

    Hey,

    I am trying to implement recursive bubble sort method and have got a response
    HTML Code:
    ArrayIndexOutOfBoundsException: 11
    Unable to figure out where I went wrong...

    HTML Code:
    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;
    }

  • #2
    arr.length is one more than the maximum index. Your swap is doing n+1, so that on the last loop your n+1 would actually be arr.length, which is out of bounds. As such your test should be n > (arr.length - 2)

    Remember, if you have an array

    ['a', 'b', 'c']

    array.length is 3, but value 'a' is array[0] and 'c' is array[2].

    I'm just surprised you're not blowing out the stack with that type of recursion. There's a reason conventional loops are usually used for this type of thing.
    Bleed your death upon me, let your bloodline feed my youth.
    https://cutcodedown.com
    https://medium.com/@deathshadow

    Comment

    Working...
    X