My Java textbook says that you can use the following code to randomly shuffle any given array:
for(int i = myList.length-1; i >=0; i--)
{
int j = (int)( Math.random() * (i+1) );
double temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
}
Would the following code that I wrote would be equally efficient or valid?
for(int i = 0; i < myList.length; i++)
{
int j = (int)( Math.random() * (myList.length) );
double temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
}
I tested my code and it does shuffle the elements properly. Is there any reason to use the textbook's algorithm over this one?