Guide · Algorithms · Sorting

Sorting – Learning Guide

Sorting is one of the first algorithms you should learn: a sorted array is easier to search, duplicates and the smallest and largest elements are found faster in it, and many greedy algorithms start precisely with sorting.

The guide goes from simple O(n²) algorithms, through efficient O(n log n) ones, to the sort function used in competitions.

  • Grades 5–8 and secondary school
  • C++
  • Competition preparation
For competitors: you should understand the algorithms from the first and second levels (they appear in questions and as ideas in other tasks), but solutions almost always use sort from the <algorithm> library.

Some lessons linked below are available only in Serbian for now. They are marked (SR).

1 Simple algorithms

Algorithms that are easy to understand and write – for arrays of up to a few thousand elements.

2 Efficient O(n log n) algorithms

Divide and conquer: how a million numbers are sorted in a fraction of a second.

3 Sorting in practice

What is really written in a competition.

4 Tasks and further topics

A collection of tasks and topics that rely on sorting.

Suggested order

  1. Selection, insertion and bubble sort
  2. Merge sort
  3. Quicksort
  4. The sort function in C++ (SR)
  5. Counting sort (SR)
  6. Tasks with solutions

Useful external resources

  • CSES Problem Set – the "Sorting and Searching" section, tasks with automatic checking
  • Petlja – collections of tasks in Serbian with automatic checking
  • VisuAlgo – Sorting – step-by-step animations of all sorting algorithms