0

I am writing a program that generates 10k random integers in the main class and then bubble-sorts it and returns the count of how many times the array was sorted. The problem is that even though I got the method to be public and return the count, it always shows up to means 0 after running it.

METHOD

  public int bubbleSort(int bub[], int count){
    int n = bub.length;
    for(int i=0;i<n-1;i++)
      for(int j=0;j<n-i-1;j++)
        if(bub[j]>bub[j+1]){
          int temp = bub[j];
          bub[j] = bub[j+1];
          bub[j+1] = temp;
          count++;
        }
        return count;
  }
      void printArray(int bub[]){
        int n = bub.length;
        for(int i=0;i<n;i++){
        System.out.print(bub[i] + " " );
        }
      }
}

MAIN CLASS

import java.util.Random;
class Main{
  public static void main(String args[]){
    Random rd = new Random();
    Bubble ob = new Bubble();
    int count=0;
    int[] bub = new int[10000];
    for(int i=0;i<bub.length;i++){
    bub[i] = rd.nextInt(100);
    }
    ob.bubbleSort(bub, count);
    System.out.println(count);
    System.out.println("sorted array");
    ob.printArray(bub);
   System.out.println("number of times array was sorted " + count);
  }
}
José Luiz
  • 45
  • 3
  • 3
    Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – OH GOD SPIDERS Feb 11 '21 at 17:32
  • In short: Don't have count as a method parameter you pass, because with javas pass-by-value any changes you make to the primitive int aren't reflected in the original pased reference. Instead work with the actual return value from your method (`int count = b.bubbleSort(....)`) – OH GOD SPIDERS Feb 11 '21 at 17:34
  • I understand what the post says but I can't understand what to fix in the code to make it work. – José Luiz Feb 11 '21 at 17:35
  • 1
    @JoséLuiz Just use a local value in the sort to count the iterations. Then return that value. – WJS Feb 11 '21 at 17:36
  • I see it, so i such add a line saying ```count = ob.bubbleSort(bub, count)``` ? – José Luiz Feb 11 '21 at 17:38
  • @JoséLuiz Since the passed count parameter is useless i would recommend just getting rid of it so that in the end your code will look like `int count = ob.bubbleSort(bub);` – OH GOD SPIDERS Feb 11 '21 at 17:40

1 Answers1

0

Because int is a primitive type the count variable won't get modified in your function.

change

ob.bubbleSort(bub, count); 

to

count = ob.bubbleSort(bub, count);