Bitpath

Lesson 1 · Unit 04

The sort you already have

In place or a copy, and the trap in the default order

12 exercisesabout 3 min

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(" "));

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.

One email when Bitpath is ready to try. Nothing else. Privacy