Search code examples
bubble-sort

To return number of swaps in the bubble sort


Why this getNumSwaps() method do not return the value of instance variable numberOfSwaps

In the main function the method is called but its fruitless

public class Solution {
 public int numberOfSwaps;
Solution(){} 
   public int[] bubbleSort(int[] x){  // To sort the array
    for (int i = 0; i < x.length; i++) {  
        for (int j = 0; j < x.length - 1; j++) {
            if (x[j] > x[j + 1]) {
               int tmp = x[j];
                x[j] = x[j + 1];
                x[j + 1] = tmp;
              this.numberOfSwaps++;//This counts the number of Swaps  
             }
         }
         if (numberOfSwaps == 0) {
        break;
         }
   }
    return x;
}
public int getNumOfSwaps(){ //this method returns zero. ??
    return this.numberOfSwaps;
}

 public static void main(String[] args) {
         Scanner sc=new Scanner(System.in);
         int arrLength=sc.nextInt();int i=0;
          int [] myArry=new int[arrLength];
          Solution sln=new Solution();   
          while(i<arrLength){
            myArry[i]=sc.nextInt();
             i++; 
        }
      System.out.println("Array is sorted in "+sln.getNumOfSwaps()+" swaps.");
      System.out.println("First Element: "+sln.bubbleSort(myArry)[0]+
                         "\nLast Element: "+sln.bubbleSort(myArry)[arrLength-1]);  
 }
}

Solution

  • You are calling getNumOfSwaps() before you actually sort the array, hence you are getting the default value of zero. Your main() method should look something like this:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arrLength = sc.nextInt();
        int i = 0;
        int[] myArry = new int[arrLength];
        Solution sln = new Solution();   
        while (i < arrLength) {
            myArry[i] = sc.nextInt();
            i++; 
        }
    
        // first sort the array, populating the number of swaps counter
        int[] myArrySorted = sln.bubbleSort(myArry);
    
        // then access the number of swaps counter
        System.out.println("Array is sorted in " + sln.getNumOfSwaps() + " swaps.");
        System.out.println("First Element: " + myArrySorted[0] +
                           "\nLast Element: "  + myArrySorted[arrLength-1]);
    }
    

    I am also assuming that your implementation of bubble sort be correct. In any case, my answer should explain the reason you were getting zero instead of some value.