Question

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;
            }
        }
    }
}
Was it helpful?

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.

OTHER TIPS

I'll echo what Jim has said in the comments. Being resourceful is an important skill as a software developer. A Google search would have quickly turned up a helpful article like this one.

You need to use the Random class to accomplish this.

Random randomGenerator = new Random();
int array = new int[100];
for (int idx = 0; idx < 100; ++idx){
  array[idx] = randomGenerator.nextInt(100) + 1;
}

Note on the usage of the nextInt(int n) method:

It produces a pseudo-random integer between 0 (inclusive) and the specified integer (exclusive). That is the reason for adding 1 to the output of nextInt(100) as it shifts your output range from 0-99 to 1-100 as desired.

public void generateRandom()
{
   int[] x = new int[100]; // This initializes an array of length 100
   Random rand = new Random();
   for(int i = 0; i < 100; i++)
   {
       x[i] = rand.nextInt(100); // Use the random class to generate random integers (and give boundaries)
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top