Sorting Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Sorting.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

Rearranging items in a collection into a defined order, such as smallest to largest or alphabetical.

Putting things in order—alphabetical, numerical, by date—so they are easier to find and use.

Read the full concept explanation →

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Different sorting algorithms have different efficiency trade-offs and work better in different situations.

Common stuck point: Stable sort preserves original order of equal elements; unstable doesn't.

Worked Examples

Example 1

medium
Sort the list [5, 2, 8, 1, 9] using bubble sort. Show the first two passes.

Solution

  1. 1
    Step 1: Pass 1 — compare adjacent pairs and swap if needed: (5,2)→swap→[2,5,8,1,9], (5,8)→ok, (8,1)→swap→[2,5,1,8,9], (8,9)→ok. After pass 1: [2,5,1,8,9].
  2. 2
    Step 2: Pass 2: (2,5)→ok, (5,1)→swap→[2,1,5,8,9], (5,8)→ok, (8,9)→ok. After pass 2: [2,1,5,8,9].
  3. 3
    Step 3: Continue until no swaps occur. Bubble sort has O(n^2) time complexity.

Answer

After pass 1: [2,5,1,8,9]. After pass 2: [2,1,5,8,9]. Final: [1,2,5,8,9].
Bubble sort repeatedly passes through the list, swapping adjacent elements that are in the wrong order. The largest unsorted element 'bubbles' to its correct position each pass.

Example 2

hard
Compare bubble sort and merge sort in terms of time complexity. When would you choose one over the other?

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
Sort [4, 1, 3] using insertion sort. Show each step.

Example 2

medium
You have a list of exam scores that is already sorted except one new score was added at the end. Would insertion sort or bubble sort be a better choice, and why?

Background Knowledge

These ideas may be useful before you work through the harder examples.

arrayalgorithm