Sorting an Array in Random Order











up vote
9
down vote

favorite
2












I'm trying to understand how sorting an array in random order works. So, I found the following code:






var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);





my main question is why they use 0.5 not another number?
and how it really works please try to make it simple i'm new in javascript and i'm struggling with these things










share|improve this question
























  • Why you passed func into your sort() function for sorting an array of string ?
    – KolaCaine
    Dec 3 at 10:26






  • 4




    terminologically it's not sorting but shuffling using sort function
    – sertsedat
    Dec 3 at 10:38






  • 1




    also please refer to the answer from the question @ponury-kostek linked: stackoverflow.com/a/18650169/3729695
    – sertsedat
    Dec 3 at 10:42






  • 6




    This is a bad idea - the sort predicate should be consistent. If for whatever reason you compare a and b twice, the result should be the same. And in general, it should also consistent. (So a<b and b<c imply a<c, or a>b and b>c imply a>c - the choice of order is independent from the need for consistency)
    – MSalters
    Dec 3 at 11:55






  • 2




    "how it really works?" - it doesn't work at all! See also robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
    – Bergi
    Dec 3 at 12:07

















up vote
9
down vote

favorite
2












I'm trying to understand how sorting an array in random order works. So, I found the following code:






var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);





my main question is why they use 0.5 not another number?
and how it really works please try to make it simple i'm new in javascript and i'm struggling with these things










share|improve this question
























  • Why you passed func into your sort() function for sorting an array of string ?
    – KolaCaine
    Dec 3 at 10:26






  • 4




    terminologically it's not sorting but shuffling using sort function
    – sertsedat
    Dec 3 at 10:38






  • 1




    also please refer to the answer from the question @ponury-kostek linked: stackoverflow.com/a/18650169/3729695
    – sertsedat
    Dec 3 at 10:42






  • 6




    This is a bad idea - the sort predicate should be consistent. If for whatever reason you compare a and b twice, the result should be the same. And in general, it should also consistent. (So a<b and b<c imply a<c, or a>b and b>c imply a>c - the choice of order is independent from the need for consistency)
    – MSalters
    Dec 3 at 11:55






  • 2




    "how it really works?" - it doesn't work at all! See also robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
    – Bergi
    Dec 3 at 12:07















up vote
9
down vote

favorite
2









up vote
9
down vote

favorite
2






2





I'm trying to understand how sorting an array in random order works. So, I found the following code:






var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);





my main question is why they use 0.5 not another number?
and how it really works please try to make it simple i'm new in javascript and i'm struggling with these things










share|improve this question















I'm trying to understand how sorting an array in random order works. So, I found the following code:






var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);





my main question is why they use 0.5 not another number?
and how it really works please try to make it simple i'm new in javascript and i'm struggling with these things






var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);





var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);






javascript arrays sorting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 3 at 17:33









rv7

1,8731322




1,8731322










asked Dec 3 at 10:22









Med Amine Elwere

594




594












  • Why you passed func into your sort() function for sorting an array of string ?
    – KolaCaine
    Dec 3 at 10:26






  • 4




    terminologically it's not sorting but shuffling using sort function
    – sertsedat
    Dec 3 at 10:38






  • 1




    also please refer to the answer from the question @ponury-kostek linked: stackoverflow.com/a/18650169/3729695
    – sertsedat
    Dec 3 at 10:42






  • 6




    This is a bad idea - the sort predicate should be consistent. If for whatever reason you compare a and b twice, the result should be the same. And in general, it should also consistent. (So a<b and b<c imply a<c, or a>b and b>c imply a>c - the choice of order is independent from the need for consistency)
    – MSalters
    Dec 3 at 11:55






  • 2




    "how it really works?" - it doesn't work at all! See also robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
    – Bergi
    Dec 3 at 12:07




















  • Why you passed func into your sort() function for sorting an array of string ?
    – KolaCaine
    Dec 3 at 10:26






  • 4




    terminologically it's not sorting but shuffling using sort function
    – sertsedat
    Dec 3 at 10:38






  • 1




    also please refer to the answer from the question @ponury-kostek linked: stackoverflow.com/a/18650169/3729695
    – sertsedat
    Dec 3 at 10:42






  • 6




    This is a bad idea - the sort predicate should be consistent. If for whatever reason you compare a and b twice, the result should be the same. And in general, it should also consistent. (So a<b and b<c imply a<c, or a>b and b>c imply a>c - the choice of order is independent from the need for consistency)
    – MSalters
    Dec 3 at 11:55






  • 2




    "how it really works?" - it doesn't work at all! See also robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
    – Bergi
    Dec 3 at 12:07


















Why you passed func into your sort() function for sorting an array of string ?
– KolaCaine
Dec 3 at 10:26




Why you passed func into your sort() function for sorting an array of string ?
– KolaCaine
Dec 3 at 10:26




4




4




terminologically it's not sorting but shuffling using sort function
– sertsedat
Dec 3 at 10:38




terminologically it's not sorting but shuffling using sort function
– sertsedat
Dec 3 at 10:38




1




1




also please refer to the answer from the question @ponury-kostek linked: stackoverflow.com/a/18650169/3729695
– sertsedat
Dec 3 at 10:42




also please refer to the answer from the question @ponury-kostek linked: stackoverflow.com/a/18650169/3729695
– sertsedat
Dec 3 at 10:42




6




6




This is a bad idea - the sort predicate should be consistent. If for whatever reason you compare a and b twice, the result should be the same. And in general, it should also consistent. (So a<b and b<c imply a<c, or a>b and b>c imply a>c - the choice of order is independent from the need for consistency)
– MSalters
Dec 3 at 11:55




This is a bad idea - the sort predicate should be consistent. If for whatever reason you compare a and b twice, the result should be the same. And in general, it should also consistent. (So a<b and b<c imply a<c, or a>b and b>c imply a>c - the choice of order is independent from the need for consistency)
– MSalters
Dec 3 at 11:55




2




2




"how it really works?" - it doesn't work at all! See also robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
– Bergi
Dec 3 at 12:07






"how it really works?" - it doesn't work at all! See also robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
– Bergi
Dec 3 at 12:07














5 Answers
5






active

oldest

votes

















up vote
7
down vote



accepted










You used



var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);


And here the most important thing is as.sort(func).
func(a,b) will return value in range of [-0.5,0.5].



Because this function return 0.5 - Math.random() and Math.random() will return the float value which is in range of [0,1].
So that your func will return value in range of [-0.5,0.5].



And this mean that sort order will be set increase or decrease.
this is random.
So your result will be random






var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return Math.random();
}

console.log(s);








var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0 - Math.random();
}

console.log(s);








var as = ["max","jack","sam"];  
var s = as.sort(func);

function func(a, b) {
return 0.5 - Math.random();
}

console.log(s);








share|improve this answer



















  • 1




    Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
    – BallpointBen
    Dec 3 at 18:20






  • 1




    @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
    – Bergi
    Dec 3 at 20:00


















up vote
7
down vote













Math.random() returns a number between 0 and 1 (exclusive). We're using 0.5 because it is the mean value.



Array.sort() sorts the parameters based on the return value. So, 0.5 - Math.random() will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.



How it really works




  • If the return value of Array.sort is positive, then the index of the
    first parameter will be higher than that of the second.

  • If it is negative, then the index of the second parameter will be
    higher than that of the first.

  • And, if it is 0, then do nothing.






share|improve this answer






























    up vote
    5
    down vote













    Math.random() return random value between 0 to 1 (0 is included but 1 is excluded).
    So 0.5 act as mid point. If use use value like greater than 1 or less 0 than it will always be either true or false.
    So for this reason 0.5 is used.



    You can read more here about Math.random()



    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random




    Let's understand it bit more with examples







    var as = ["max","jack","sam"];  
    var s = as.sort(func);

    function func(a, b) {
    return 0.5 - Math.random();
    }

    console.log(s);





    This is what you get when you use value greater than 1






    var as = ["max","jack","sam"];  
    var s = as.sort(func);

    function func(a, b) {
    return 1 - Math.random();
    }

    console.log(s);





    This is what happens when you use value less than 0






    var as = ["max","jack","sam"];  
    var s = as.sort(func);

    function func(a, b) {
    return -1 - Math.random();
    }

    console.log(s);





    P.S :-




    1. Try printing output from all the above condition you will see that last two condition will always return either true or false from function. so you will not get a random sorting.


    2. Now talk about any value from 0 to 0.99 you can use any value but 0.5 will serve your purpose best.Because it's a middle point you're most likely to get best answer.







    share|improve this answer






























      up vote
      1
      down vote













      Math.random returns a number between 0 and 1.



      Sorting function use the return value x as the following :




      • x == 0 : Same value, can order "how it wants"


      • x < 0 : the first object is less than the second one, therefore its index in the sorted array will be less than the other's


      • x > 0 same as x < 0 but the other way around



      Since Math.random returns a number between 0 and 1 and we want to also get negative numbers, we must subtract some value.
      Here 0.5 - Math.random() would give a number between 0.5 and -0.5






      share|improve this answer




























        up vote
        0
        down vote













        If you call the sort method with a function parameter is called several times. This function should accept two parameters (let's call the first A and the second B) Each time it should return a value:




        1. Less than zero, if A < B

        2. Equal to zero, if A = B

        3. Greater the zero, if A > B


        So in this example we need random return values that evenly distribute negative and positive values. Since Math.random() returns a value between 0 and 1, 0.5 - Math.random() will return values between -0.5 and 0.5, which meets the requirements.






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53591691%2fsorting-an-array-in-random-order%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          7
          down vote



          accepted










          You used



          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);


          And here the most important thing is as.sort(func).
          func(a,b) will return value in range of [-0.5,0.5].



          Because this function return 0.5 - Math.random() and Math.random() will return the float value which is in range of [0,1].
          So that your func will return value in range of [-0.5,0.5].



          And this mean that sort order will be set increase or decrease.
          this is random.
          So your result will be random






          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0 - Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);








          share|improve this answer



















          • 1




            Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
            – BallpointBen
            Dec 3 at 18:20






          • 1




            @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
            – Bergi
            Dec 3 at 20:00















          up vote
          7
          down vote



          accepted










          You used



          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);


          And here the most important thing is as.sort(func).
          func(a,b) will return value in range of [-0.5,0.5].



          Because this function return 0.5 - Math.random() and Math.random() will return the float value which is in range of [0,1].
          So that your func will return value in range of [-0.5,0.5].



          And this mean that sort order will be set increase or decrease.
          this is random.
          So your result will be random






          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0 - Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);








          share|improve this answer



















          • 1




            Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
            – BallpointBen
            Dec 3 at 18:20






          • 1




            @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
            – Bergi
            Dec 3 at 20:00













          up vote
          7
          down vote



          accepted







          up vote
          7
          down vote



          accepted






          You used



          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);


          And here the most important thing is as.sort(func).
          func(a,b) will return value in range of [-0.5,0.5].



          Because this function return 0.5 - Math.random() and Math.random() will return the float value which is in range of [0,1].
          So that your func will return value in range of [-0.5,0.5].



          And this mean that sort order will be set increase or decrease.
          this is random.
          So your result will be random






          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0 - Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);








          share|improve this answer














          You used



          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);


          And here the most important thing is as.sort(func).
          func(a,b) will return value in range of [-0.5,0.5].



          Because this function return 0.5 - Math.random() and Math.random() will return the float value which is in range of [0,1].
          So that your func will return value in range of [-0.5,0.5].



          And this mean that sort order will be set increase or decrease.
          this is random.
          So your result will be random






          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0 - Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);








          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return Math.random();
          }

          console.log(s);





          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return Math.random();
          }

          console.log(s);





          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0 - Math.random();
          }

          console.log(s);





          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0 - Math.random();
          }

          console.log(s);





          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);





          var as = ["max","jack","sam"];  
          var s = as.sort(func);

          function func(a, b) {
          return 0.5 - Math.random();
          }

          console.log(s);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 3 at 10:47

























          answered Dec 3 at 10:29









          Jin

          483116




          483116








          • 1




            Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
            – BallpointBen
            Dec 3 at 18:20






          • 1




            @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
            – Bergi
            Dec 3 at 20:00














          • 1




            Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
            – BallpointBen
            Dec 3 at 18:20






          • 1




            @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
            – Bergi
            Dec 3 at 20:00








          1




          1




          Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
          – BallpointBen
          Dec 3 at 18:20




          Crucially, a value of 0.5 makes the probability that one element is evaluated to be less than another exactly 1/2, which makes the random sort unbiased with respect to the initial order of the list.
          – BallpointBen
          Dec 3 at 18:20




          1




          1




          @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
          – Bergi
          Dec 3 at 20:00




          @BallpointBen That's simply wrong. Using Math.random() in sort does not lead to unbiased results.
          – Bergi
          Dec 3 at 20:00












          up vote
          7
          down vote













          Math.random() returns a number between 0 and 1 (exclusive). We're using 0.5 because it is the mean value.



          Array.sort() sorts the parameters based on the return value. So, 0.5 - Math.random() will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.



          How it really works




          • If the return value of Array.sort is positive, then the index of the
            first parameter will be higher than that of the second.

          • If it is negative, then the index of the second parameter will be
            higher than that of the first.

          • And, if it is 0, then do nothing.






          share|improve this answer



























            up vote
            7
            down vote













            Math.random() returns a number between 0 and 1 (exclusive). We're using 0.5 because it is the mean value.



            Array.sort() sorts the parameters based on the return value. So, 0.5 - Math.random() will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.



            How it really works




            • If the return value of Array.sort is positive, then the index of the
              first parameter will be higher than that of the second.

            • If it is negative, then the index of the second parameter will be
              higher than that of the first.

            • And, if it is 0, then do nothing.






            share|improve this answer

























              up vote
              7
              down vote










              up vote
              7
              down vote









              Math.random() returns a number between 0 and 1 (exclusive). We're using 0.5 because it is the mean value.



              Array.sort() sorts the parameters based on the return value. So, 0.5 - Math.random() will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.



              How it really works




              • If the return value of Array.sort is positive, then the index of the
                first parameter will be higher than that of the second.

              • If it is negative, then the index of the second parameter will be
                higher than that of the first.

              • And, if it is 0, then do nothing.






              share|improve this answer














              Math.random() returns a number between 0 and 1 (exclusive). We're using 0.5 because it is the mean value.



              Array.sort() sorts the parameters based on the return value. So, 0.5 - Math.random() will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.



              How it really works




              • If the return value of Array.sort is positive, then the index of the
                first parameter will be higher than that of the second.

              • If it is negative, then the index of the second parameter will be
                higher than that of the first.

              • And, if it is 0, then do nothing.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 3 at 14:52









              wjandrea

              9321228




              9321228










              answered Dec 3 at 10:27









              rv7

              1,8731322




              1,8731322






















                  up vote
                  5
                  down vote













                  Math.random() return random value between 0 to 1 (0 is included but 1 is excluded).
                  So 0.5 act as mid point. If use use value like greater than 1 or less 0 than it will always be either true or false.
                  So for this reason 0.5 is used.



                  You can read more here about Math.random()



                  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random




                  Let's understand it bit more with examples







                  var as = ["max","jack","sam"];  
                  var s = as.sort(func);

                  function func(a, b) {
                  return 0.5 - Math.random();
                  }

                  console.log(s);





                  This is what you get when you use value greater than 1






                  var as = ["max","jack","sam"];  
                  var s = as.sort(func);

                  function func(a, b) {
                  return 1 - Math.random();
                  }

                  console.log(s);





                  This is what happens when you use value less than 0






                  var as = ["max","jack","sam"];  
                  var s = as.sort(func);

                  function func(a, b) {
                  return -1 - Math.random();
                  }

                  console.log(s);





                  P.S :-




                  1. Try printing output from all the above condition you will see that last two condition will always return either true or false from function. so you will not get a random sorting.


                  2. Now talk about any value from 0 to 0.99 you can use any value but 0.5 will serve your purpose best.Because it's a middle point you're most likely to get best answer.







                  share|improve this answer



























                    up vote
                    5
                    down vote













                    Math.random() return random value between 0 to 1 (0 is included but 1 is excluded).
                    So 0.5 act as mid point. If use use value like greater than 1 or less 0 than it will always be either true or false.
                    So for this reason 0.5 is used.



                    You can read more here about Math.random()



                    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random




                    Let's understand it bit more with examples







                    var as = ["max","jack","sam"];  
                    var s = as.sort(func);

                    function func(a, b) {
                    return 0.5 - Math.random();
                    }

                    console.log(s);





                    This is what you get when you use value greater than 1






                    var as = ["max","jack","sam"];  
                    var s = as.sort(func);

                    function func(a, b) {
                    return 1 - Math.random();
                    }

                    console.log(s);





                    This is what happens when you use value less than 0






                    var as = ["max","jack","sam"];  
                    var s = as.sort(func);

                    function func(a, b) {
                    return -1 - Math.random();
                    }

                    console.log(s);





                    P.S :-




                    1. Try printing output from all the above condition you will see that last two condition will always return either true or false from function. so you will not get a random sorting.


                    2. Now talk about any value from 0 to 0.99 you can use any value but 0.5 will serve your purpose best.Because it's a middle point you're most likely to get best answer.







                    share|improve this answer

























                      up vote
                      5
                      down vote










                      up vote
                      5
                      down vote









                      Math.random() return random value between 0 to 1 (0 is included but 1 is excluded).
                      So 0.5 act as mid point. If use use value like greater than 1 or less 0 than it will always be either true or false.
                      So for this reason 0.5 is used.



                      You can read more here about Math.random()



                      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random




                      Let's understand it bit more with examples







                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 0.5 - Math.random();
                      }

                      console.log(s);





                      This is what you get when you use value greater than 1






                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 1 - Math.random();
                      }

                      console.log(s);





                      This is what happens when you use value less than 0






                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return -1 - Math.random();
                      }

                      console.log(s);





                      P.S :-




                      1. Try printing output from all the above condition you will see that last two condition will always return either true or false from function. so you will not get a random sorting.


                      2. Now talk about any value from 0 to 0.99 you can use any value but 0.5 will serve your purpose best.Because it's a middle point you're most likely to get best answer.







                      share|improve this answer














                      Math.random() return random value between 0 to 1 (0 is included but 1 is excluded).
                      So 0.5 act as mid point. If use use value like greater than 1 or less 0 than it will always be either true or false.
                      So for this reason 0.5 is used.



                      You can read more here about Math.random()



                      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random




                      Let's understand it bit more with examples







                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 0.5 - Math.random();
                      }

                      console.log(s);





                      This is what you get when you use value greater than 1






                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 1 - Math.random();
                      }

                      console.log(s);





                      This is what happens when you use value less than 0






                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return -1 - Math.random();
                      }

                      console.log(s);





                      P.S :-




                      1. Try printing output from all the above condition you will see that last two condition will always return either true or false from function. so you will not get a random sorting.


                      2. Now talk about any value from 0 to 0.99 you can use any value but 0.5 will serve your purpose best.Because it's a middle point you're most likely to get best answer.







                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 0.5 - Math.random();
                      }

                      console.log(s);





                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 0.5 - Math.random();
                      }

                      console.log(s);





                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 1 - Math.random();
                      }

                      console.log(s);





                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return 1 - Math.random();
                      }

                      console.log(s);





                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return -1 - Math.random();
                      }

                      console.log(s);





                      var as = ["max","jack","sam"];  
                      var s = as.sort(func);

                      function func(a, b) {
                      return -1 - Math.random();
                      }

                      console.log(s);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Dec 3 at 10:40

























                      answered Dec 3 at 10:26









                      Code Maniac

                      78014




                      78014






















                          up vote
                          1
                          down vote













                          Math.random returns a number between 0 and 1.



                          Sorting function use the return value x as the following :




                          • x == 0 : Same value, can order "how it wants"


                          • x < 0 : the first object is less than the second one, therefore its index in the sorted array will be less than the other's


                          • x > 0 same as x < 0 but the other way around



                          Since Math.random returns a number between 0 and 1 and we want to also get negative numbers, we must subtract some value.
                          Here 0.5 - Math.random() would give a number between 0.5 and -0.5






                          share|improve this answer

























                            up vote
                            1
                            down vote













                            Math.random returns a number between 0 and 1.



                            Sorting function use the return value x as the following :




                            • x == 0 : Same value, can order "how it wants"


                            • x < 0 : the first object is less than the second one, therefore its index in the sorted array will be less than the other's


                            • x > 0 same as x < 0 but the other way around



                            Since Math.random returns a number between 0 and 1 and we want to also get negative numbers, we must subtract some value.
                            Here 0.5 - Math.random() would give a number between 0.5 and -0.5






                            share|improve this answer























                              up vote
                              1
                              down vote










                              up vote
                              1
                              down vote









                              Math.random returns a number between 0 and 1.



                              Sorting function use the return value x as the following :




                              • x == 0 : Same value, can order "how it wants"


                              • x < 0 : the first object is less than the second one, therefore its index in the sorted array will be less than the other's


                              • x > 0 same as x < 0 but the other way around



                              Since Math.random returns a number between 0 and 1 and we want to also get negative numbers, we must subtract some value.
                              Here 0.5 - Math.random() would give a number between 0.5 and -0.5






                              share|improve this answer












                              Math.random returns a number between 0 and 1.



                              Sorting function use the return value x as the following :




                              • x == 0 : Same value, can order "how it wants"


                              • x < 0 : the first object is less than the second one, therefore its index in the sorted array will be less than the other's


                              • x > 0 same as x < 0 but the other way around



                              Since Math.random returns a number between 0 and 1 and we want to also get negative numbers, we must subtract some value.
                              Here 0.5 - Math.random() would give a number between 0.5 and -0.5







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Dec 3 at 10:31









                              Vivick

                              1,2461317




                              1,2461317






















                                  up vote
                                  0
                                  down vote













                                  If you call the sort method with a function parameter is called several times. This function should accept two parameters (let's call the first A and the second B) Each time it should return a value:




                                  1. Less than zero, if A < B

                                  2. Equal to zero, if A = B

                                  3. Greater the zero, if A > B


                                  So in this example we need random return values that evenly distribute negative and positive values. Since Math.random() returns a value between 0 and 1, 0.5 - Math.random() will return values between -0.5 and 0.5, which meets the requirements.






                                  share|improve this answer



























                                    up vote
                                    0
                                    down vote













                                    If you call the sort method with a function parameter is called several times. This function should accept two parameters (let's call the first A and the second B) Each time it should return a value:




                                    1. Less than zero, if A < B

                                    2. Equal to zero, if A = B

                                    3. Greater the zero, if A > B


                                    So in this example we need random return values that evenly distribute negative and positive values. Since Math.random() returns a value between 0 and 1, 0.5 - Math.random() will return values between -0.5 and 0.5, which meets the requirements.






                                    share|improve this answer

























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      If you call the sort method with a function parameter is called several times. This function should accept two parameters (let's call the first A and the second B) Each time it should return a value:




                                      1. Less than zero, if A < B

                                      2. Equal to zero, if A = B

                                      3. Greater the zero, if A > B


                                      So in this example we need random return values that evenly distribute negative and positive values. Since Math.random() returns a value between 0 and 1, 0.5 - Math.random() will return values between -0.5 and 0.5, which meets the requirements.






                                      share|improve this answer














                                      If you call the sort method with a function parameter is called several times. This function should accept two parameters (let's call the first A and the second B) Each time it should return a value:




                                      1. Less than zero, if A < B

                                      2. Equal to zero, if A = B

                                      3. Greater the zero, if A > B


                                      So in this example we need random return values that evenly distribute negative and positive values. Since Math.random() returns a value between 0 and 1, 0.5 - Math.random() will return values between -0.5 and 0.5, which meets the requirements.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Dec 3 at 14:19









                                      gsamaras

                                      49.1k2398179




                                      49.1k2398179










                                      answered Dec 3 at 10:31









                                      HerrSerker

                                      19.4k84777




                                      19.4k84777






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53591691%2fsorting-an-array-in-random-order%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                          Alcedinidae

                                          Origin of the phrase “under your belt”?