Marshall McCurdy
Marshall McCurdy

Reputation: 55

I am supposed to be generating random numbers, however if you run it, im getting more a lot of repeats is, that natural or did i mess up?

I am supposed to be generating an array with 1000 numbers in it and then bubble sorting it. the output i get has quite a bit of repeated numbers, a little too much and i feel like i have messed up. I am still learning so go easy on me:)

public static void main(String[] args) {

    Random rd = new Random();
int[] arr = new int[1000];

for (int i = 0; i < arr.length; i++ ) {
    arr[i] = (int)(Math.random()*1000+1);



int n = arr.length;
int temp = 0;

for(int z=0; z < n; z++){
for(int j=1; j < (n-z); j++){                        
   if(arr[j-1] > arr[j]){

        temp = arr[j-1];
        arr[j-1] = arr[j];
        arr[j] = temp;

   }                    
   }
   }


    System.out.println(arr[i]);

Upvotes: 0

Views: 50

Answers (1)

Powersjd
Powersjd

Reputation: 60

Your main issue is that you are still initializing your array while you are attempting to sort through it. The following approach seems to give what you expected.

I wrote a quick little solution using the Random class that I find to be a little cleaner since it already has a .nextInt that you can seed with a max value you can visually make it a little cleaner.

    static void myRandom() {
        Random rand = new Random();
        int[] arr = new int[1000];

        for(int i = 0; i < arr.length; i++){
            arr[i] = rand.nextInt(1000) + 1;
            System.out.println(arr[i]);
        }
    }

Upvotes: 1

Related Questions