0

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]);
  • 2
    You're not using `rd`, why do you instantiate it? Other than that, what do you mean you get too many repeated numbers? Have you calculated any probabilities that suggest that what you're seeing would be unlikely assuming you were randomizing right? – G. Bach Apr 18 '20 at 21:29
  • 1
    Why are you initializing a Random object (rd) but not using it? The Random class is better than Math.random(). See this post: https://stackoverflow.com/questions/738629/math-random-versus-random-nextintint – Tom Cools Apr 18 '20 at 21:30
  • 1
    Your generating 1000 random numbers between 1 and 1000, it is almost guaranteed that your gonna have some duplicates. If you dont want duplicates, generate a sorted array with a 1000 numbers, then shuffle it. – steviestickman Apr 18 '20 at 22:04
  • 1
    You should expect to get duplicate values, see https://en.wikipedia.org/wiki/Birthday_problem. In fact, the probability of at least one duplicate value is around 0.99 by the time you've sampled 100 values in the range [1, 1000]. – pjs Apr 18 '20 at 23:08
  • thank you all so much – Marshall McCurdy Apr 18 '20 at 23:22

1 Answers1

1

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]);
        }
    }
Powersjd
  • 60
  • 1
  • 7
  • 1
    You probably don't want to use the phrase "seed with a max value" to discuss parameterizing the range. Seed has a very specific meaning in the context of PRNGs. – pjs Apr 19 '20 at 01:59