Search code examples
javaarrayssortingswapbubble-sort

Bubble sort not working when swapping done separately


My code works only when i am using the swap inside the function of bubble sort,but if i remove the part and put it inside a function and then call it to use as swap .It doesn't works and gives me a wrong output.What is wrong i cant understand

public class BubbleSort
{
  void swap(int a, int b)
  {
    int temp;
    temp = a;
    a = b;
    b = temp;
  }
  
  void sort(int arr[])
  {
    int i, j, n=arr.length;
    
    for(i=0; i<n-1; i++)
    {
      for(j=0; j<(n-i-1); j++)
      {
        if(arr[j] > arr[j+1])
          swap(arr[j], arr[j+1]);
      }
    }
  }
  
  public static void main(String[] args)
  {
    int i;
    int arr[] = {12, 3, 4, 10, 40, 89, 60, 55, 96, 11};
    BubbleSort ob = new BubbleSort();
    ob.sort(arr);
    System.out.println("Array after sorting:");
    for(i=0; i<arr.length; i++)
      System.out.print(arr[i] + " ");
  }
}

Solution

  • Method arguments in Java are passed by value, never by reference. Assignments like this make no sense:

    void swap(int a, int b)  {
      int temp;
      temp = a;
      a = b;
      b = temp;
    }
    

    The caller outside of this method won't see this. For him "a" and "b" will remain their old values.

    As a quick workaround you can use AtomicInteger instances to wrap values.