Back

Activity 2.11: Raylib Lab 9 — Visualizing a Search

In classBuilt in class, straight after Activity 2.10's deck.

divider

What You're Building

An array drawn as a row of bars, and a search you step through one press of Space at a time. The bar being checked turns yellow, the bars the search has ruled out go dark, and the target turns green when it is found. By the end you will watch linear search and binary search side by side — and watch binary search throw away the very bar it is looking for.

Twelve bars of increasing height labeled 8 to 91. The six on the left are dark gray, the bar labeled 67 is green, and the rest are light blue. The text reads Binary search for 67. Checks: 2, and Found at index 8.

Task 3: binary search finds 67 in two presses

divider

Activity 2.11

Raylib Lab 9 — Visualizing a Search

Key Concepts

An Array You Can See

Color Carries the State

One Press, One Check

Watching a Search Go Wrong

Activity 2.10's Search Finished Before You Could Blink

The loop in Find ran all of its checks in a fraction of a millisecond. The only way to see what happened inside was to trace low, mid and high by hand.

This lab slows the search down to your speed and draws every step: which element it is checking, which ones it has already ruled out, and where it ends up.

The Array Becomes a Row of Bars

Each element becomes a bar. Its index decides where it goes: index 0 at the left, every next index a little further right. Its value decides how tall it is. One method, DrawBar, draws any bar you name by its index.

The array is sorted, so the bars climb from left to right.

The Array Becomes a Row of Bars

Twelve light blue bars rising from left to right, labeled 8, 15, 21, 30, 37, 44, 52, 60, 67, 75, 83, 91

Color Shows What the Search Knows

Four colors, four states: yellow is the bar being checked right now, dark gray is ruled out, green is found, and light blue is still possible.

Predict: binary search for 67 checks the middle first. What does the row look like after one press?

Color Shows What the Search Knows

The bar labeled 44 is yellow, the five bars to its left are dark gray, and the six to its right are light blue

44 is too small for 67, so everything from 44 leftward is ruled out in one check. Nothing about the search changed from Activity 2.10. You can just see it now.

The while Becomes an if

In Activity 2.10, a while loop repeated the check until the edges crossed.

Demo
while (low <= high)
{
// one check: look at mid, move an edge
}

The while Becomes an if

A Raylib program is already a loop, running sixty times a second. So the search does not need its own: an if does one check, on the one frame Space goes down.

Demo
if (Raylib.IsKeyPressed(KeyboardKey.Space) && low <= high)
{
// one check: look at mid, move an edge
}

You are the loop now. Each press is one pass, and the check count stops being a number in the output and becomes how many times you pressed.

Linear Darkens One Bar a Press; Binary Darkens Half

Linear search for 67 rules out one bar per press, left to right, and needs nine presses to reach it.

Binary search rules out half of what is left per press, and needs two. On twelve bars that is a small difference. On a million it is the difference between a million presses and twenty.

Watch Binary Search Throw the Target Away

Swap two values so the array is no longer sorted: 67 and 91 trade places. 67 is still in the array, at the far right.

Predict what binary search for 67 does now.

Watch Binary Search Throw the Target Away

Every bar is dark gray except one yellow bar labeled 60. The bar labeled 67, at the far right, is gray. The text reads Not in the list.

“Not in the list,” with 67 standing right there in gray. It was ruled out by a check that trusted the array to be sorted. Activity 2.10's silent failure, made visible.

Build It Now, Then One Last Check

You build it now, on the classroom computers — Raylib does not run in Juicemind.

Before the end of the session you will be asked to make one change and predict what it does before you run it. A student who built the lab can answer in seconds; that is the whole check.

Today's Objectives

  • Drawing an array as bars with a method that takes an index and a color
  • Using color to show the state of a search
  • Stepping linear and binary search one check per key press
  • Watching binary search fail on an unsorted array

Key Terms

Visualization
A picture of data or a process that makes its shape visible.
State
What a program currently knows; here, which bar it is checking and what it has ruled out.
Ruled out
An element the search has decided cannot be the target, and will never check again.

'F' → Fullscreen

divider

Build

Create a new Raylib program named 2-11-search.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.

This lab runs on the classroom computers, not in Juicemind. Close the window to end the program. Escape works too.


Task 1: The Array as Bars

  • DrawBar takes an index and a color. It works out the bar's x from the index and its height from the value at that index, then draws the bar and its value underneath.
  • Write the code below and run it. Then change one number in values and run it again. Only one bar should change. Put it back.
  • DrawBar has two parameters, but the index ends up deciding two things about the bar. Write down which two, and what the color parameter decides.
2-11-search
#:package Raylib-cs@8.0.0
using Raylib_cs;
int[] values = { 8, 15, 21, 30, 37, 44, 52, 60, 67, 75, 83, 91 };
Raylib.InitWindow(800, 450, "Search");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.DarkBlue);
for (int i = 0; i < values.Length; i++)
{
DrawBar(i, Color.SkyBlue);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();
void DrawBar(int index, Color color)
{
int x = 40 + index * 62;
int height = values[index] * 3;
Raylib.DrawRectangle(x, 360 - height, 46, height, color);
Raylib.DrawText($"{values[index]}", x + 12, 372, 20, Color.White);
}

Task 2: Linear Search, One Press at a Time

  • current is the index being checked, starting at -1 (nothing checked yet), and found is where the target turned up. Each press of Space checks the next bar. BarColor decides each bar's color from those two numbers, and the drawing loop hands it to DrawBar.
  • Make the changes shown and run it. Press Space until 67 is found. Record the number of checks.
  • Change target to 40, which is not in the array, and press through. Record the checks when it says it is not there.
2-11-search
#:package Raylib-cs@8.0.0
using Raylib_cs;
int[] values = { 8, 15, 21, 30, 37, 44, 52, 60, 67, 75, 83, 91 };
int target = 67;
int current = -1;
int found = -1;
Raylib.InitWindow(800, 450, "Search");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
if (Raylib.IsKeyPressed(KeyboardKey.Space) && found == -1 && current < values.Length - 1)
{
current = current + 1;
if (values[current] == target)
{
found = current;
}
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.DarkBlue);
for (int i = 0; i < values.Length; i++)
{
DrawBar(i, BarColor(i));
}
Raylib.DrawText($"Linear search for {target}. Checks: {current + 1}", 40, 20, 24, Color.White);
if (found != -1)
{
Raylib.DrawText($"Found at index {found}", 40, 410, 20, Color.Green);
}
else if (current == values.Length - 1)
{
Raylib.DrawText("Not in the list", 40, 410, 20, Color.Red);
}
else
{
Raylib.DrawText("Press Space to check the next bar", 40, 410, 20, Color.LightGray);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();
void DrawBar(int index, Color color)
{
int x = 40 + index * 62;
int height = values[index] * 3;
Raylib.DrawRectangle(x, 360 - height, 46, height, color);
Raylib.DrawText($"{values[index]}", x + 12, 372, 20, Color.White);
}
Color BarColor(int index)
{
if (index == found)
{
return Color.Green;
}
if (index == current)
{
return Color.Yellow;
}
if (index < current)
{
return Color.DarkGray;
}
return Color.SkyBlue;
}

Task 3: Binary Search, One Press at a Time

  • Now each press does one pass of Activity 2.10's loop: low and high mark the bars still possible, and mid is the one being checked. Anything outside the edges is ruled out.
  • Make the changes shown, with target back at 67, and press through. Record the checks, and compare with Task 2.
  • Search for 40 again and record the checks. Then search for 91 and for 8, the two ends, and record both.
2-11-search
#:package Raylib-cs@8.0.0
using Raylib_cs;
int[] values = { 8, 15, 21, 30, 37, 44, 52, 60, 67, 75, 83, 91 };
int target = 67;
int low = 0;
int high = values.Length - 1;
int mid = -1;
int found = -1;
int checks = 0;
Raylib.InitWindow(800, 450, "Search");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
if (Raylib.IsKeyPressed(KeyboardKey.Space) && found == -1 && low <= high)
{
mid = (low + high) / 2;
checks = checks + 1;
if (values[mid] == target)
{
found = mid;
}
else if (values[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.DarkBlue);
for (int i = 0; i < values.Length; i++)
{
DrawBar(i, BarColor(i));
}
Raylib.DrawText($"Binary search for {target}. Checks: {checks}", 40, 20, 24, Color.White);
if (found != -1)
{
Raylib.DrawText($"Found at index {found}", 40, 410, 20, Color.Green);
}
else if (low > high)
{
Raylib.DrawText("Not in the list", 40, 410, 20, Color.Red);
}
else
{
Raylib.DrawText("Press Space to check the middle bar", 40, 410, 20, Color.LightGray);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();
void DrawBar(int index, Color color)
{
int x = 40 + index * 62;
int height = values[index] * 3;
Raylib.DrawRectangle(x, 360 - height, 46, height, color);
Raylib.DrawText($"{values[index]}", x + 12, 372, 20, Color.White);
}
Color BarColor(int index)
{
if (index == found)
{
return Color.Green;
}
if (index == mid)
{
return Color.Yellow;
}
if (index < low || index > high)
{
return Color.DarkGray;
}
return Color.SkyBlue;
}

Task 4: Break It on Purpose

  • On line 5, swap 67 and 91, so the array is no longer sorted. Set target back to 67.
  • Press through the search. Take a screenshot of where it ends.
  • Explain why the bar for 67 is gray. Find the check that threw it away: what did the search compare there, and what did it decide?
2-11-search
#:package Raylib-cs@8.0.0
using Raylib_cs;
int[] values = { 8, 15, 21, 30, 37, 44, 52, 60, 91, 75, 83, 67 };
int target = 67;
int low = 0;
int high = values.Length - 1;
int mid = -1;
int found = -1;
int checks = 0;
Raylib.InitWindow(800, 450, "Search");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
if (Raylib.IsKeyPressed(KeyboardKey.Space) && found == -1 && low <= high)
{
mid = (low + high) / 2;
checks = checks + 1;
if (values[mid] == target)
{
found = mid;
}
else if (values[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.DarkBlue);
for (int i = 0; i < values.Length; i++)
{
DrawBar(i, BarColor(i));
}
Raylib.DrawText($"Binary search for {target}. Checks: {checks}", 40, 20, 24, Color.White);
if (found != -1)
{
Raylib.DrawText($"Found at index {found}", 40, 410, 20, Color.Green);
}
else if (low > high)
{
Raylib.DrawText("Not in the list", 40, 410, 20, Color.Red);
}
else
{
Raylib.DrawText("Press Space to check the middle bar", 40, 410, 20, Color.LightGray);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();
void DrawBar(int index, Color color)
{
int x = 40 + index * 62;
int height = values[index] * 3;
Raylib.DrawRectangle(x, 360 - height, 46, height, color);
Raylib.DrawText($"{values[index]}", x + 12, 372, 20, Color.White);
}
Color BarColor(int index)
{
if (index == found)
{
return Color.Green;
}
if (index == mid)
{
return Color.Yellow;
}
if (index < low || index > high)
{
return Color.DarkGray;
}
return Color.SkyBlue;
}

Challenge (Optional): Start Again

  • Make R reset the search, so you can step through it again without restarting the program. Every variable that changes during a search has to go back to its starting value.
  • Then make the Up and Down keys change target by 1 before a search starts, and show the target on screen.
divider

Checkpoint

Every picture here is a screenshot of this page's own programs, with the key presses played back automatically.

Linear search for 67 after nine checks: the eight bars on the left are dark gray, 67 is green, and the three on the right are light blue

Task 2, linear search finds 67

Binary search on the scrambled array: every bar gray except a yellow 60, and the text Not in the list

Task 4, 67 and 91 swapped

  • DrawBar draws every bar, and BarColor decides every color
  • Each press of Space does exactly one check, in both searches
  • You recorded the checks for 67 and 40 with both searches, and for 91 and 8 with binary search
  • You have a screenshot of Task 4 and an explanation of the gray 67
divider

Reflection

Answer the following questions before submitting your work.

  1. The search logic in Task 3 is the same as Activity 2.10's. What did watching it change about your understanding, if anything? An honest “nothing” is fine if you can say why.
  2. Linear search for 40 took twelve presses and binary search took four. How many presses would each need on an array of 1000 bars, in the worst case?
  3. DrawBar and BarColor are yours; the key check for Space is not. Explain which part of the Create task's rules decides that.
divider

Submit

Submit four things to the dropbox:

  1. Your 2-11-search program file, in its Task 4 form.
  2. Your Task 4 screenshot.
  3. Your Task 1 answer about the parameters, and every check count from Tasks 2 and 3.
  4. Your three reflection answers.

Activity Complete