Home > Web Front-end > JS Tutorial > An example of JS implementing random sorting function

An example of JS implementing random sorting function

零下一度
Release: 2017-06-17 17:19:06
Original
1422 people have browsed it

This article mainly introduces the random sorting function algorithm implemented by JS, and analyzes javascriptcommonly used sorting algorithm implementation techniques based on specific examples. Friends in need can refer to the following

The example in this article describes the random sorting function algorithm implemented by JS. Share it with everyone for your reference, the details are as follows:

Use JS to write a method to randomly arrange the elements in the array every time they are refreshed

Method 1:

var arr =[1,2,3,4];
var t;
for(var i = 0;i < arr.length; i++){
 var rand = parseInt(Math.random()*arr.length);
   t = arr[rand];
   arr[rand] =arr[i];
   arr[i] = t;
}
console.log(arr);
Copy after login

Method two:

var arr =[1,2,3,4];
var brr = [];
var num = arr.length;
for (var i = 0; i < num; i++){
 var temp = parseInt(Math.random()*(num-i));
 brr.push(arr[temp]);
 arr.splice(temp,1);
}
console.log(brr);
Copy after login

Method three:---best way.

function randomsort(a, b) {
  return Math.random()>.5 ? -1 : 1; //通过随机产生0到1的数,然后判断是否大于0.5从而影响排序,产生随机性的效果。
}
var arr = [1, 2, 3, 4, 5];
arr.sort(randomsort);
Copy after login

The above is the detailed content of An example of JS implementing random sorting function. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template