Search code examples
javaarrayssortingbubble-sort

How to prompt user to input a number to get size of array. Then sort array using bubble sort method


Haven't practiced Java in a long while so any help would be appreciated.

For the class project, we have to create a program that prompts the user to input a number and creates the size of an array. After input, we are to show the list of numbers before it is sorted and a list after it has been sorted using the bubble sort algorithm.

Here is what I have so far. I know I'm missing a chunk of code so that I can get the list to print both before and after sorting, but I'm lost.

import java.util.Scanner;
public class Part1BubbleSort  
{
public static void main(String[] args) 
{
    //int temp = 0;

    Scanner scan = new Scanner(System.in);
    int z = scan.nextInt();
    int [] array = new int[z];
    System.out.print("Please enter a number to create array."+"\n");
    z = scan.nextInt();

    //Bubble Sort
    for(int i = array.length-1; i>=0; i--)
    {
        for(int j=0; j<i; j++)
        {
            if(array[j] > array[j+1])
            {
                int temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
    }
}

Solution

  • You could do as follows:

    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.Random;
    public class BubbleTest {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.println("Please enter a number to create array."+"\n");
            int z = scan.nextInt();
            int [] array = new int[z];
            // Randomly generating array elements
    
            for(int i =0; i<z; i++){
                array[i]=new Random().nextInt();
            }
          //  z = scan.nextInt();
            System.out.println("Unsorted:");
            System.out.println(Arrays.toString(array));
    
    
            //Bubble Sort
            for(int i = array.length-1; i>=0; i--)
            {
                for(int j=0; j<i; j++)
                {
                    if(array[j] > array[j+1])
                    {
                        int temp = array[j];
                        array[j] = array[j+1];
                        array[j+1] = temp;
                    }
                }
            }
    
            System.out.println("sorted:");
            System.out.println(Arrays.toString(array));
        }
    
    }