Given an array, it is required to randomly disrupt the order of elements in the array, and then output, mainly to ensure efficiency. This algorithm is actually simple. First, we randomly select one element from all the elements to exchange with the first element, and then select one element after the second to exchange with the second element until the last element. This ensures that the probability of each element at each position is 1/n.
Given an array, it is required to randomly disrupt the order of elements in the array, and then output, mainly to ensure efficiency.
This algorithm is actually simple. First, we randomly select one element from all the elements to exchange with the first element, and then select one element after the second to exchange with the second element until the last element. This ensures that the probability of each element at each position is 1/n. The code is as follows:
# Include
# Include
# Include
// Randomly disrupt an array void random (int a [], int n) {int index, tmp, I; srand (time (NULL); for (I = 0; I
Disrupt the order of an array, such as shuffling.
The following is implemented using Java:
Import java. util. random; public class RandomSort {private Random random = new Random (); // array SIZE private static final int SIZE = 10; // the array private int [] positions = new int [SIZE]; public RandomSort () {for (int index = 0; index
= 0; index --) {// a random value is obtained from 0 to the index, and exchange (random) with the element at the index. nextInt (index + 1), index);} dwn ();} // switch location private void exchange (int p1, int p2) {int temp = positions [p1]; positions [p1] = positions [p2]; positions [p2] = temp;} // Print the array value private void dwn () {for (int index = 0; index
However, the random number generated by the random number generator is not random, so the sorting result page has many similarities. A better random number generator can achieve better results and be used for shuffling.
Address of this article: http://www.nowamagic.net/librarys/veda/detail/491,welcome.