Data structures and algorithms · Lesson 24 of 60 · Code lesson, JavaScript or Python · Optional
Sorting algorithms
Sorting puts items in order, which makes searching and comparing much easier.
Bubble sort swaps neighbours that are out of order, and insertion sort slides each item into its place.
Merge sort and quicksort split the work into smaller parts, which is much faster on big lists.
Worked example
In JavaScript, swapping two items needs a temporary variable so neither value is lost.
const numbers = [3, 1, 2];
numbers.sort((a, b) => a - b);
console.log(numbers.join(" "));Output: 1 2 3
In Python, a, b = b, a swaps two values in one line.
numbers = [3, 1, 2]
numbers.sort()
print(" ".join(map(str, numbers)))Output: 1 2 3
Your turn
This bubble sort compares neighbours but never swaps them. Add the swap so the numbers print in order, smallest first.
Your program is checked with these 3 inputs:
Input:
3 1 2
Expected output:
1 2 3
Input:
5 4 3 2 1
Expected output:
1 2 3 4 5
Input:
1 2
Expected output:
1 2
Loading your practice…
Preparing your workspace…