0

I am trying to sort the array using bubble sort algo in Java. But when I run the code an ArrayIndexOutofBoundException occurs. Here is my code

package bubblesort;

public class BubbleSort {

    public int[] sort(int [] arr){
    int temp=0;
        for(int i=0 ; i<arr.length ; i++)
            for(int j=0 ; j<arr.length-i ; j++){
                if(arr[j] > arr[j+1])
                {
                temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
                }}
        return arr;
    }    

    public static void main(String[] args) {

       BubbleSort ob = new BubbleSort();
       int[]nums={2,5,1,55};
       System.out.println("Sorted list is:");
       int[]sorted =ob.sort(nums);
       for(int i=0 ; i<nums.length;i++)
            System.out.println(nums[i]);            
    }
}
Mureinik
  • 252,575
  • 45
  • 248
  • 283
abdul rafay
  • 141
  • 8
  • 2
    Is there a reason for the `c`-tag or do you just find it aesthetically pleasing? – EOF Jan 14 '17 at 11:43
  • 1
    Where is the C part of your question? – Gerhardh Jan 14 '17 at 11:43
  • @EOF Hilarious comment +1 – Tim Biegeleisen Jan 14 '17 at 11:43
  • Note on terminology: the exception is thrown when you **run**, or **execute** the code. Not when you **compile** it. When you ask about an exception, **always** post the complete stack trace of the exception (and read it before, because it contains a lot of useful information). – JB Nizet Jan 14 '17 at 11:50

1 Answers1

1

Since your inner loop references arr[j+1], it should terminate one step sooner, and not iterate up to the last element:

for(int i = 0 ; i < arr.length; i++)
    for(int j = 0 ; j  < arr.length - i - 1; j++) {
        // Here ------------------------^
Mureinik
  • 252,575
  • 45
  • 248
  • 283