0

I have to write a bubble sort program, and I have it coded out, but for some reason my outputs are totally insane. This is SOME of the outputs... the list goes all the way to 190 repeating the same thing; "[I@5b787144"

49, 21, 45, 22, 28, 55, 91, 34, 69, 27, 40, 60, 41, 14, 45, 79, 93, 11, 89, 77, 1)[I@5b787144
2)[I@5b787144
3)[I@5b787144

Here is my code.

import java.util.Random;

public class Bubble 
{
   public void generate ()
    {  
       int k;
       int a[];
       int count = 1;
       a = new int[20];
       for (int i = 0; i < 20; i++)
       {
            Random rand = new Random();
            a[i] = rand.nextInt(100);
            System.out.print(a[i] +", ");
       }
       for (int h = 0; h < a.length-1; h++)
       {
            for (int j = 1; j < a.length-h; j++)
                {
                    if (a[j-1] > a[j])
                    {
                        k = a[j-1];
                        a[j-1] = a[j];
                        a[j] = k;
                    }

                    System.out.println(+count+ ")" +a);
                    count++;
                }
       }
    }
}

I need it to sort it in ascending order, while also printing out every iteration of the sort.

  • check out [Arrays.toString()](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(int[])) – BevynQ Apr 28 '16 at 02:20

1 Answers1

0

You print a, which is an object. It is trying to print the memory address of that object. You want to print all the elements in the array. I suggest you write a helper method for that, since you do it multiple places:

private void printArr(int[] array) {
 for (int i : array) {
  System.out.print(i + "");
 }
 System.out.println();
}

Then instead of calling

System.out.println(+count+ ")" +a);

Do

System.out.print(count + "");
printArr(a);
nhouser9
  • 6,730
  • 3
  • 21
  • 42