Lesson 1 · Unit 04
The sort you already have
In place or a copy, and the trap in the default order
What you practise
- In-place vs new list
- JavaScript's default string comparison
- Comparators
Try a question from this lesson
Pick one
The built-in sort is called with no arguments on a list of numbers. What does this print?
nums = [10, 9, 1, 100]
nums.sort()
print(*nums)const nums = [10, 9, 1, 100];
nums.sort();
console.log(nums.join(" "));const nums = [10, 9, 1, 100];
nums.sort();
console.log(nums.join(" "));Correct answer
1 9 10 100
1 10 100 9
1 10 100 9
Why
Python compares numbers as numbers: 1 9 10 100. JavaScript and TypeScript, given no comparator, compare items as text, so 100 lands before 9 just as "apple" lands before "b": 1 10 100 9.
JavaScript noteThe default sort() converts every item to a string first. It is right for strings and wrong for numbers.
TypeScript noteTypeScript does not warn here: sort() with no comparator is valid on a number[], even though the result is rarely what you want.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Use the built-in sort
Every language ships a sort that is O(n log n), stable and heavily tuned. Use it.
Python sorts numbers by value out of the box. JavaScript and TypeScript need a comparator for numbers: a function that takes two items and returns a negative number when the first one should come first. For numbers, a - b does exactly that.
nums = [10, 9, 1, 100]
nums.sort()
print(*nums)const nums = [10, 9, 1, 100];
nums.sort((a, b) => a - b);
console.log(nums.join(" "));const nums = [10, 9, 1, 100];
nums.sort((a, b) => a - b);
console.log(nums.join(" "));Python notePython's sort is Timsort: a merge sort that uses insertion sort on short runs. Both ideas come from the last two units.
JavaScript note(a, b) => a - b is negative when a is smaller, so smaller numbers come first.
TypeScript note(a, b) => a - b needs no annotations: TypeScript knows a and b are number because nums is a number[].
10 more exercises in the app
- 4× multiple choice
- 2× type the answer
- 1× fill the blanks
- 2× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.