← Back to course
Code Crew G3 / Week 07 / Wednesday
3/6
Week 07 Β· Algorithms

Wednesday

// Best way to solve it

Wednesday: Two Sort Algorithms

Rocket and Raven each have a way to sort cards. Rocket's way picks the smallest card again and again. Raven's way swaps cards that sit side by side.

"Mine is better!" Rocket says. Raven smiles. "Let's test both plans on the same cards."

Nova adds a second puzzle. "Once cards are sorted, we can find one card faster." Let's help them try both sorting plans.

Here are TWO different ways to sort cards. Both work; try each one on the same set.

ALGORITHM A: 'Pick the Smallest'
    REPEAT UNTIL no cards left:
        find the SMALLEST card
        move it to the end of a 'sorted' pile
ALGORITHM B: 'Bubble it Up'
    REPEAT UNTIL no swaps happen:
        for each pair of side-by-side cards:
            IF left > right: swap them

Try both on: 4, 1, 3, 2

Algorithm A, show each step:
________________________________
________________________________
Algorithm B, show each step:
________________________________
________________________________

Searching

SEARCH is finding something in a group. Two famous algorithms:

LINEAR SEARCH:
    look at every item one by one
    stop when you find it

BINARY SEARCH (only on a sorted list):
    look at the MIDDLE item
    IF it is what you want β†’ done
    IF too big β†’ search the LEFT half
    IF too small β†’ search the RIGHT half

Search Practice

Linear search looks at items one by one. Binary search jumps to the middle of a sorted list.

Each binary guess cuts the list in half.

LINEAR OR BINARY?
  • Read the question.
  • Tap your answer.
List: 2, 5, 7, 9, 12. Linear search for 9. How many items do you check?
Same list. Binary search starts with which number?
You want 9. The middle is 7. Which half do you search next?
Can binary search work on an unsorted pile?
Sorted list: 1, 3, 4, 6, 8, 10, 11. Which number is in the middle?
You want 10. Is 10 bigger or smaller than the middle?
Which half do you search next: left or right?
StatementTrue or false?
Linear search checks items one at a time.?
Binary search starts at the middle.?
Binary search works on any messy pile.?
Each binary guess throws away about half the list.?
WHY THIS EXERCISEChoosing the right search makes finding things much faster.
Try it
Play guess my number from 1 to 20 with a grown-up.
They say higher or lower after each guess.
Always guess the middle of what is left. Count your guesses.

Quick test

Which is faster on a sorted phone book? ____
WHY THIS EXERCISEBinary search gives fast lookup in sorted data.
Which works on an unsorted pile? ____
← Tuesday