Repository navigation
Sorting Algorithms
Examples
- Sorting numbers from smallest to largest
- Sorting names alphabetically
- Sorting movies based on release year
Why do we need to learn this?
. Sorting is an incredibly common taks, so it's good to know how it works . there are many different ways to sort things, and different techniques have their own advantages and disadvantages
...but it doesn't always work the way you expect
example:
["Steele", "Colt", "Data Structure", "Algorithms"].sort() =>
["Algorithms", "Colt", "Data Structures", "Steele"]
that make sense, that sorted alphabetically.
another example:
[6, 4, 15, 10].sort() => [10, 15, 4, 6] => that does not make sense.
. The built-in sort method accepts an optional comparator funtion . You can use this comparator function to tell JavaScript how you want it to sort . The comparator looks at pairs of elements (a and b), determines their order on the return value . If it returns a negative number, a should come before b . If it returns positive number, it should come after b . If it returns 0, a and b are the same as far as the sort is concerned
example:
function numberCompare(num1, num2) {
return num1 - num2;
}
[6, 4, 15, 10].sort(numberCompare); // [4, 6, 10, 15]