Search code examples
javasortingindexoutofboundsexceptionbubble-sort

Sorting of array by bubble sort


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]);            
    }
}

Solution

  • 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 ------------------------^