Can anyone tell me plz why does subtracting a - b sort the numbers in numerical order? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Can anyone tell me plz why does subtracting a - b sort the numbers in numerical order?

var myArray = [10, 44, 32, 100, 0, 44, 3, 4]; document.write(myArray); // 10, 44, 32, 100, 0, 44, 3, 4 myArray.sort(); document.write(myArray); // 0,10,100,3,32,4,44,44 myArray.sort(function (a, b) { return a - b; }); document.write(myArray); // 0,3,4,10,32,44,44,100 And also How do all the numbers get sorted into proper order if the function is only examining 2 numbers at a time? (i.e. a and b)

11th Apr 2020, 12:49 PM
Nikhil Maroju
Nikhil Maroju - avatar
2 Answers
+ 1
1. Substraction gives negative(b>a), positive(a>b) or zero(a==b) value depending on relation between numbers. 2. Learn some basic sorting algorithms like bubble sort https://www.w3resource.com/javascript-exercises/javascript-function-exercise-24.php.
11th Apr 2020, 1:21 PM
Stephan
Stephan - avatar
+ 1
Actually I knew about bubble sort before but little confused about having function as argument in sort() anyway TQ for Ur answer ..
11th Apr 2020, 1:30 PM
Nikhil Maroju
Nikhil Maroju - avatar