23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

We show <strong>in</strong> Code Fragment 3.8 a short (but complete) <strong>Java</strong> program that uses the<br />

methods above.<br />

Code Fragment 3.8: Test program ArrayTest<br />

that uses various built-<strong>in</strong> methods of the Arrays<br />

class.<br />

Program ArrayTest uses another feature <strong>in</strong> <strong>Java</strong>—the ability to generate<br />

pseudor<strong>and</strong>omnumbers, that is, numbers that are statistically r<strong>and</strong>om (but not<br />

truly r<strong>and</strong>om). In particular, it uses a java.util.R<strong>and</strong>om object, which is a<br />

pseudo-r<strong>and</strong>om number generator, that is, an object that computes, or<br />

"generates," a sequence of numbers that are statistically r<strong>and</strong>om. Such a generator<br />

needs a place to start, however,which is its seed. The sequence of numbers<br />

generated for a given seed will always be the same. In our program, we set the<br />

seed to the current time <strong>in</strong> milliseconds s<strong>in</strong>ce January 1, 1970 (us<strong>in</strong>g the method<br />

System.currentTimeMillis), which will be different each time we run<br />

our program. Once we have set the seed, we can repeatedly get a r<strong>and</strong>om number<br />

between 0 <strong>and</strong> 99 by call<strong>in</strong>g the nextInt method with argument 100. We show<br />

a sample output of this program below:<br />

arrays equal before sort: true<br />

arrays equal after sort: false<br />

old = [41,38,48,12,28,46,33,19,10,58]<br />

154

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!