javaarrayssortingrecursionbubble-sort

Recursive Bubble Sort in Java


I am trying to write a Recursive Bubble sort in Java and I'm getting an Index Out of Bounds Exception. What am I doing wrong and why am I getting this error? Here is my code:

public static  <T extends Comparable< ? super T>>
    void sort(T [] a){
    T tmp;
    for(int i=0;i<a.length;i++){
        if(a[i].compareTo(a[i+1])>0){
            tmp = a[i];
            a[i]=a[i+1];
            a[i+1]=tmp;
            sort(a);
        }
        System.out.println("i:"+i+" "+a[i]);

    }

Also, even tho it sorts the array and I get the error at the end, it is printing all of the steps, how do I make it print the last final sorted array? Is probably a simple answer but my brain is fried right now and can't think straight. Thanks in advance.


Solution

  • The loop should stop when i < a.length-1 , because in your code you access the position i+1, and when i == a.length - 1 then i+1 will be trying to access an element off the end of the array that doesn't exist - hence, out of bounds.