Search code examples
javarandombubble-sort

Bubble Sorting an Array of random values of 1-100


This was assignment 1.

Now I have to create the same thing but use a random array of 1-100 values and i have no clue how implement that into what i already have.

public class Test {

    public static void main(String a[]) {
    int i;



    int[] array = {9,1,5,8,7,2,1,5,5,6,8,15,3,9,19,18,88,10,1,100,4,8};
    System.out.println("Values Before the sort:\n");
    for (i = 0; i < array.length; i++)
        System.out.print(array[i] + "  ");
    System.out.println();
    bubble_srt(array, array.length);
    System.out.print("Values after the sort:\n");
    for (i = 0; i < array.length; i++)
        System.out.print(array[i] + "  ");
    System.out.println();



}

public static void bubble_srt(int a[], int n) {
    int i, j, t = 0;
    for (i = 0; i < n; i++) {
        for (j = 1; j < (n - i); j++) {
            if (a[j - 1] > a[j]) {
                t = a[j - 1];
                a[j - 1] = a[j];
                a[j] = t;
            }
        }
    }
}

Solution

  • You need to use a random generator to get the numbers. For an array of size X it would be something like this:

    int[] array = new int[X];
    Random random = new Random();
    
    for (int i = 0; i < X; i++)
        array[i] = random.nextInt(100) + 1;
    

    You should take a look at the documentation for Random.