Search code examples
javaiobubble-sort

Not getting correct output after implementing bubbleSort


This program creates a file named datafile.txt and writes 100 integers created randomly into the file using text I/O. I also implemented bubbleSort to sort the numbers in ascending order, but it's not sorting them. Plus, the output to command line is "The sorted numbers are: [I@f72617" 100 times. Thanks in advance.

   import java.io.*;
   import java.util.Random;

   public class Lab5 {

//sort array
static int[] bubbleSort(int[] array) {

    for (int pass = 1; pass <= 100; pass++) {
        for (int current = 0; current < 100-pass; current++) {

            //compare element with next element
            if (array[current] > array[current + 1]) {

                //swap array[current] > & array[current + 1]
                int temp = array[current];
                array[current] = array[current + 1];
                array[current + 1] = temp;
            } //end if
        }
    }
    return array;
}
public static void main(String args[]) {

    //Open file to write to
    try {
        FileOutputStream fout = new FileOutputStream("F:\\IT311\\datafile.txt");


    int index = 0;

    //Convert FileOutputStream into PrintStream 
    PrintStream myOutput = new PrintStream(fout);
    Random numbers = new Random();
        //Declare array
        int array[] = new int[100];
        for (int i = 0; i < array.length; i++)
        {
        //get the int from Random Class
        array[i] = (numbers.nextInt(100) + 1);

        myOutput.print(array[i] + " ");

        //sort numbers
        int[] sortedArray = bubbleSort(array);

        //print sorted numbers
        System.out.print("The sorted numbers are: ");
        System.out.print(sortedArray);
        }
    }
    catch (IOException e) {
        System.out.println("Error opening file: " + e);
        System.exit(1);
    }
}

}


Solution

  • Use below:

    System.out.print(Arrays.toString(sortedArray));