Simple Example of random sorting of javascript Arrays

Source: Internet
Author: User

In js, there is no such thing as php that can be used directly to sort data randomly. Here we will write a custom random array sorting function.

There are many ways to randomly arrange javascript arrays. The following is a simple method:

The Code is as follows: Copy code

Function randomSort (a, B ){
Return Math. random ()>. 5? -1:1;
}


If the random number is greater than 0.5,-1 is returned, that is, a is before B. If the random number is less than 0.5, 1 is returned, that is, B is before.

A company's interview question: Randomly disconnects 1-numbers and places them in the JS array. Then, write a function: specify the number of 1-numbers, quickly finds the subscript index number corresponding to this number from the array.

The Code is as follows: Copy code

Var writable r = [];
For (var I = 0; I <100; I ++ ){
Pull R. push (I); // pull R [I] = I;
}
Function randomSort (a, B) {// random arrangement of array elements
Return Math. random ()>. 5? -1:1;
}
Using R. sort (randomSort );

Function showIndex (num ){
For (var j = 0; j <partition R. length; j ++ ){
If (distinct R [j] = num ){
Console. log (j); // output to the console
Break;
}
}
}
ShowIndex (43 );


There are many ways to disrupt Arrays

The Code is as follows: Copy code

Function randomsort (a, B ){
Return Math. random ()>. 5? -1: 1;

// Use the Math. random () function to generate 0 ~ The random number between 1 and 0.5 is compared, and-1 or 1 is returned.
}
Var arr = [1, 2, 3, 4, 5];
Var arr2 = arr. sort (randomsort );
Alert (arr2 );


Arrayobj. sort ([sortfunction])

This method sorts Array objects appropriately. During execution, no new Array objects are created.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.