The use of shuffle algorithm in Java _java

Source: Internet
Author: User
Tags generator rand shuffle

Fisher–yates Shuffle basic idea (Knuth Shuffle):

To shuffle A of n elements (indices 0..n-1):
For i-n−1 downto 1 Do
J←random integer with 0≤j≤i
Exchange A[j] and A[i]

JDK source code is as follows:

Copy Code code as follows:

/**
* Moves every element of the list to a random new position in the list.
*
* @param list
* The List to Shuffle
*
* @throws unsupportedoperationexception
* When replacing a element in the ' not ' supported
*/
public static void Shuffle (List<?> List) {
Shuffle (list, new Random ());
}

/**
* Moves every element of the list to a random new position in the list
* Using the specified random number generator.
*
* @param list
* The List to Shuffle
* @param random
* The random number generator
*
* @throws unsupportedoperationexception
* When replacing a element in the ' not ' supported
*/
@SuppressWarnings ("Unchecked")
public static void Shuffle (List<?> List, Random Random) {
if (!) ( List instanceof randomaccess)) {
object[] array = List.toarray ();
for (int i = array.length-1 i > 0; i--) {
int index = Random.nextint (i + 1);
if (Index < 0) {
index =-index;
}
Object temp = array[i];
Array[i] = Array[index];
Array[index] = temp;
}

int i = 0;
listiterator<object> it = (listiterator<object>) List
. Listiterator ();
while (It.hasnext ()) {
It.next ();
It.set (array[i++]);
}
} else {
List<object> rawlist = (list<object>) List;
for (int i = Rawlist.size ()-1; i > 0; i--) {
int index = Random.nextint (i + 1);
if (Index < 0) {
index =-index;
}
Rawlist.set (Index, Rawlist.set (i, Rawlist.get (index));
}
}
}


To test the code, multiple containers are used to ensure that each case is initialized:
Copy Code code as follows:

public class Javashuffle {
public static int temp = 0;
public static long start;
public static long end;

public static void Main (final String args[]) {

        Object changetemp;
        list<integer> numlist = new arraylist<integer> ();
        list<integer> firstlist = new arraylist<integer> ();
        list<integer> secondlist = new arraylist<integer> ();
        list<integer> thirdlist = new arraylist<integer> ();
        list<integer> fourthlist = new arraylist<integer> ();

        for (int i = 1; I <= 100000; i++) {
     & nbsp;      Numlist.add (i);
            Firstlist.add (i);
            Secondlist.add (i);
            Thirdlist.add (i);
            Fourthlist.add (i);
       }

       //shuffle,use changetemp
         GetStartTime ();
        int randint = 0;
        for (int i = 0, length = firstlist.size (); i < length; i++) {
 & nbsp;          Randint = Getrandom (i, firstList.size ());
            changetemp = Firstlist.get (i);
            Firstlist.set (i, Firstlist.get (Randint));
            Firstlist.set (Randint, javashuffle.temp);
       }
        getendtime ("Shuffle Run Time");

       //second Shuffle,exchange list
         GetStartTime ();
        for (int i = 0, length = secondlist.size (); i < length; i++) {
             Randint = Getrandom (i, secondlist.size ());
            Secondlist.set (i, Secondlist.set (Randint, Secondlist.get (i)));
       }
        getendtime ("Second Shuffle Run Time");

Third shuffle, change generate random int
GetStartTime ();
object[] Temparray = Thirdlist.toarray ();
Random rand = new Random ();
int j = 0;
for (int i = temparray.length-1 i > 0; i--) {
j = Rand.nextint (i + 1);
Thirdlist.set (I, Thirdlist.set (J, Thirdlist.get (i)));
}

Getendtime ("Third Shuffle Run Time");

Fourth shuffle, simulate Java shuffle
GetStartTime ();
Random Random = new Random ();
if (!) ( Fourthlist instanceof randomaccess)) {
object[] array = Fourthlist.toarray ();
for (int i = array.length-1 i > 0; i--) {
int index = Random.nextint (i + 1);
if (Index < 0) {
index =-index;
}
Object temp = array[i];
Array[i] = Array[index];
Array[index] = temp;
}

int i = 0;
listiterator<integer> it = (listiterator<integer>) fourthlist.listiterator ();
while (It.hasnext ()) {
It.next ();
It.set ((Integer) array[i++]);
}
} else {
List<integer> rawlist = (list<integer>) fourthlist;
for (int i = Rawlist.size ()-1; i > 0; i--) {
int index = Random.nextint (i + 1);
if (Index < 0) {
index =-index;
}
Rawlist.set (Index, Rawlist.set (i, Rawlist.get (index));
}
}
Getendtime ("Fourth Shuffle Run Time");

Java Shuffle
GetStartTime ();
Collections.shuffle (numlist);
Getendtime ("Java Shuffle run Time");
}

public static void Swap (int a, int b) {
Javashuffle.temp = A;
A = b;
b = javashuffle.temp;
}

public static int Getrandom (final int low, final int high) {
return (int) (Math.random () * (high-low) + low);
}

public static void GetStartTime () {
Javashuffle.start = System.nanotime ();
}

public static void Getendtime (final String s) {
Javashuffle.end = System.nanotime ();
SYSTEM.OUT.PRINTLN (S + ":" + (Javashuffle.end-javashuffle.start) + "ns");
}

}

If the value is small, such as level 100,000, the output is probably:

The Shuffle Run Time:85029499ns
Second Shuffle run Time:80909474ns
Third Shuffle run Time:71543926ns
Fourth Shuffle run Time:76520595ns
Java Shuffle run Time:61027643ns

The Shuffle Run Time:82326239ns
Second Shuffle run Time:78575611ns
Third Shuffle run Time:95009632ns
Fourth Shuffle run Time:105946897ns
Java Shuffle run Time:90849302ns

The Shuffle Run Time:84539840ns
Second Shuffle run Time:85965575ns
Third Shuffle run Time:101814998ns
Fourth Shuffle run Time:113309672ns
Java Shuffle run Time:35089693ns

The Shuffle Run Time:87679863ns
Second Shuffle run Time:79991814ns
Third Shuffle run Time:73720515ns
Fourth Shuffle run Time:78353061ns
Java Shuffle run Time:64146465ns

The Shuffle Run Time:84314386ns
Second Shuffle run Time:80074803ns
Third Shuffle run Time:74001283ns
Fourth Shuffle run Time:79931321ns
Java Shuffle run Time:86427540ns

The Shuffle Run Time:84315523ns
Second Shuffle run Time:81468386ns
Third Shuffle run Time:75052284ns
Fourth Shuffle run Time:79461407ns
Java Shuffle run Time:66607729ns


The results of multiple runs may be different, but the basic Java shuffle speed is the fastest, and the third is the second. And the first method takes the longest.

If it is level 10 million, it is probably as follows:

The Shuffle Run Time:2115703288ns
Second Shuffle run Time:3114045871ns
Third Shuffle run Time:4664426798ns
Fourth Shuffle run Time:2962686695ns
Java Shuffle run Time:3246883026ns the shuffle run Time:2165398466ns
Second Shuffle run Time:3129558913ns
Third Shuffle run Time:4147859664ns
Fourth Shuffle run Time:2911849942ns
Java Shuffle run Time:4311703487ns the shuffle run Time:2227462247ns
Second Shuffle run Time:3279548770ns
Third Shuffle run Time:4704344954ns
Fourth Shuffle run Time:2942635980ns
Java Shuffle run Time:3933172427ns the shuffle run Time:2200158789ns
Second Shuffle run Time:3172666791ns
Third Shuffle run Time:4715631517ns
Fourth Shuffle run Time:2950817535ns
Java Shuffle run Time:3387417676ns the shuffle run Time:2201124449ns
Second Shuffle run Time:3203823874ns
Third Shuffle run Time:4179926278ns
Fourth Shuffle run Time:2913690411ns
Java Shuffle run Time:3571313813ns the shuffle run Time:2163053190ns
Second Shuffle run Time:3073889926ns
Third Shuffle run Time:4493831518ns
Fourth Shuffle run Time:2852713887ns
Java Shuffle run Time:3773602415ns

As you can see, the first method is the fastest, and the fourth is the slowest. Java with shuffle speed is also not ideal.

When you are doing large data processing, consider using a different approach if the Java library is less efficient.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.