The most efficient method of array out of order is implemented in JavaScript

• 2020-03-30 04:05:12
• OfStack

Array out of order means that all the elements in an array are in the wrong order.

A common approach is to pass in a function to the array's native sort method, which returns either 1 or -1 at random to randomly arrange the elements of the array.

``````
arr.sort(function(a,b){ return Math.random()>.5 ? -1 : 1;});
``````

This is intuitive, but not very efficient. In my tests, it took about 35ms to scramble an array of 10,000 elements (firefox)

I have always had the good quality to break the casserole to the end, so I found an efficient method. (link: #)

``````
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
arr.shuffle();
``````

This method adds a function called shuffle to array.prototype -- but it doesn't matter what it's called, it just matters how efficient it is.

Take my above array of 10, 000 elements, and it only takes 7,8 milliseconds.

Increasing the array elements 10 times to 100,000 to test, the first sort method takes about 500+ms, the shuffle method takes about 40ms, and the difference is huge.

Complete test code:

``````
var count = 100000,arr = [];
for(var i=0;i.5 ? -1 : 1;});
Array.prototype.sort.call(arr,function(a,b){ return Math.random()>.5 ? -1 : 1;});
document.write(arr+'
');
var t1 = new Date().getTime();
document.write(t1-t);
//The following methods are most efficient
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
var t = new Date().getTime();
arr.shuffle();
document.write('
'+arr+'
');
var t1 = new Date().getTime();
document.write(t1-t);
``````

Also, if you've noticed the for loop in the shuffle code, it doesn't have a back half! So just for(..) There is no {.. }, can write so unexpectedly! And it worked! That's weird. I'll have to go to the blogosphere.

Related articles: