• Post Reply Bookmark Topic Watch Topic
  • New Topic

Merge Sort with Random Numbers  RSS feed

 
chris linder
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys I have a question this might be a stupid one but here goes nothing! How do i make this merge sort take on random numbers in an array instead of hard coding the numbers


 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chris, welcome to the Ranch.


Couple of things though that might help make your stay more enjoyable
- You were originally SHOUTING in your subject line and post. Plesae KeepItDown.
- When you post code, please UseCodeTags. There is a handy button for it

I've fixed it all up this time, just keep it in mind for any further questions.

To get to your question, it looks like you have a nice modular bit of code, all you have to do is create an array of random numbers.
There are a couple of options:
Math.random() will give you a Random number.
You can also use the java.util.Random class directly.

 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chris, welcome to CodeRanch!

You know how to do stuff multiple times right? Use a for-loop! For each iteration, generate a random number (take a look at java.lang.Math) and store it in your array.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you want the array filled with random numbers (in which case you can have repetition), or a random permutation of 1-N? If the former, you want Stephan’s approach. If the latter you've got a couple of options, but I'd put the numbers in a List and use Collections.shuffle().
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a quicker way to fill an array with pseudorandom numbers:
Create a Random instance.
Use its method which creates a Stream, e.g. this.
The Stream has a method which turns it to an array automatically.
Somebody else had a similar problem yesterday. This method doesn't work in Java7.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!