Thomas: Array nach Zufall neu sortieren

Beitrag lesen

Hallo
Hab spontan eine Idee für eine Sortierschleife. Ich nehm mal an, dass das Array myArray heisst.

var x; //So oft werden zwei Werte vertauscht
var tmp; //Variable für temp. Daten
var myArrLength; //Länge des Arrays
var pos1; //1. Position im Array
var pos2; //2. Position im Array
x = 100;
myArrLength = myArray.length;

for(i = 0;i < x;i++) {
 //Zufallszahlen zwischen 0 und 1 mal Läge des Arrays
 pos1 = Math.random() * myArrLength;
 pos2 = Math.random() * myArrLength;
 //Auf Ganzzahl runden
 pos1 = Math.round(pos1);
 pos2 = Math.round(pos2);
 //Werte in pos1 und pos2 vertauschen
 tmp = myArray[pos1];
 myArray[pos1] = myArray[pos2];
 myArray[pos2] = tmp;
}

Habs kurz getestet: Trägt von Zeit zu Zeit einen Wert nicht wieder korrekt in das Array ein. Probier mal selber herauszufinden, woran dies liegt (ev. an Zufallszahl). Sonst funktioniert es.

mfg

Thomas