I am taking some online introduction to algorithms course. And trying to understand while improving my javascript on the side. I think the following is correct but is there any way to improve it?
function randomGenerator() {
var x;
var myArray = [];
var copy = [];
for (x = 1; x <= 10000; x += 1) {
myArray.push(x);
}
var m = myArray.length;
var i;
while (m) {
i = Math.floor(Math.random() * myArray.length);
if (i in myArray) {
copy.push(myArray[i]);
delete myArray[i];
m--;
}
}
return copy;
}
I think the complexity here is O(n^3) because of the first for loop, the following while loop and the final if statement. Am I going about this in the right way?
EDIT: Found a better way to do this thanks to @Dukeling.
function randomGenerator() {
var x;
var myArray = [];
var t;
for ( x = 1; x <= 10000; x+=1) {
myArray.push(x);
}
var m = myArray.length;
var i;
while (m) {
i = Math.floor(Math.random() * m-=1);
t=myArray[m];
myArray[m]=myArray[i];
myArray[i]=t;
}
return myArray;
}
The complexity now reduces to O(n) linear time. (Please correct me if wrong)