Back

Activity 5.3 — Common Array Algorithms

divider

Introduction

Activity 5.3

Using traversal to solve problems

Today's Big Idea

  • Most array “algorithms” are the same loop… with different logic inside.
  • We're learning patterns you can reuse on MC and FRQs.
  • Two extras for fun: swap + binary search.

Algorithm Template (the loop shape)

// Traversal template (the "shape" of many algorithms)
for (int i = 0; i < arr.length; i++)
{
// work with arr[i]
}
  • i is the index
  • arr[i] is the element
  • Algorithms differ by what happens inside the loop

Review Patterns (Quick)

  • Sum/Average: accumulator (sum += arr[i])
  • Count: loop + if + counter (count++)
  • Min/Max: track best-so-far and update

Min/Max Pattern (why start at index 1?)

// Max pattern (start with first element)
int max = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
  • We initialize with arr[0] so max starts as a real value.
  • Then we compare the rest (starting at index 1).

Swap Algorithm (precursor to sorting)

Goal: exchange two elements without losing either value.

// Swap pattern (requires a temp variable)
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
  • temp holds one value safely
  • Without temp, you overwrite and lose data
  • This is the “move” used in many sorting methods

Linear Search (AP Required)

Idea: check every element until you find the target.

// Linear search: "check every element"
boolean found = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == target)
{
found = true;
}
}
  • Works on any array (sorted or not)
  • Can return a boolean or an index (often -1 if not found)

Binary Search (Enrichment / For Fun)

  • Requirement: array must be sorted
  • Instead of checking every element, we check the middle
  • Then we throw away half the search space
  • Not required for AP CSA

Binary Search Loop Skeleton

// Binary search (enrichment): "cut the search space"
int low = 0;
int high = arr.length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
// compare arr[mid] to target
// move low or high inward
}
  • If middle is too small → move low up
  • If middle is too big → move high down
  • If equal → found

Trace It (quick oral check)

  • Array: [2, 4, 7, 9, 12, 15], target = 12
  • mid starts at index 2 (value 7)
  • Is target left or right?

Success Today

  • You can recognize the pattern based on the goal.
  • You can write the code with correct braces + indentation.
  • You can trace what happens step-by-step.

'F' → Fullscreen

Objectives

  • icon Use array traversal to solve common problems (min/max, counting).
  • icon Use a swap algorithm to exchange two array elements.
  • icon Implement linear search and report a result (boolean and index).
  • icon Implement binary search as an optional enrichment challenge.
divider

Activity Tasks

  • icon Create a new project named Activity5-3-ArrayAlgorithms.
  • icon Complete Tasks 1 through 3. Task 4 is optional enrichment.

Task 1: Min & Max (Review)

  • icon Track the smallest and largest values in an array.
  • icon Initialize with the first element, then traverse from index 1.
Task 1 — Min & Max
public class Program
{
public static void main(String[] args)
{
// Task 1 — Review: Min & Max
int[] nums = {4, 7, 2, 9, 5};
int min = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++)
{
if (nums[i] < min)
{
min = nums[i];
}
if (nums[i] > max)
{
max = nums[i];
}
}
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}

Task 2: Swap Algorithm

  • icon Swap two elements using a temporary variable.
  • icon Print the array using traversal (one element per line).
  • icon Optional: do a second swap and print again.
Task 2 — Swap
public class Program
{
public static void main(String[] args)
{
// Task 2 — Swap Algorithm (precursor to sorting)
int[] nums = {10, 20, 30, 40};
// 1) Swap index 0 and index 3
int temp = nums[0];
nums[0] = nums[3];
nums[3] = temp;
// 2) Print each element on its own line (use traversal)
for (int i = 0; i < nums.length; i++)
{
System.out.println(nums[i]);
}
// 3) Challenge (optional): swap index 1 and index 2, then print again.
}
}

Task 3: Linear Search (AP Required)

  • icon Search for a target value.
  • icon Print both a boolean (found) and an index (foundIndex).
  • icon Use -1 as the “not found” index.
Task 3 — Linear Search
public class Program
{
public static void main(String[] args)
{
// Task 3 — Linear Search (AP Required)
int[] nums = {4, 7, 2, 9, 5};
int target = 9;
boolean found = false;
int foundIndex = -1;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] == target)
{
found = true;
foundIndex = i;
}
}
System.out.println("Found: " + found);
System.out.println("Index: " + foundIndex);
}
}

Task 4: Binary Search (Optional Enrichment)

  • icon Only works on a sorted array.
  • icon Use low, high, and mid to cut the search space in half.
  • icon Print a boolean and index just like Task 3.
Task 4 — Binary Search (Enrichment)
public class Program
{
public static void main(String[] args)
{
// Task 4 — Binary Search (ENRICHMENT / FOR FUN)
// Not required for the AP CSA exam
int[] nums = {2, 4, 7, 9, 12, 15};
int target = 12;
int low = 0;
int high = nums.length - 1;
boolean found = false;
int foundIndex = -1;
while (low <= high)
{
int mid = (low + high) / 2;
if (nums[mid] == target)
{
found = true;
foundIndex = mid;
break;
}
else if (nums[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
System.out.println("Found: " + found);
System.out.println("Index: " + foundIndex);
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
Min: 2
Max: 9
40
20
30
10
Found: true
Index: 3
Found: true
Index: 4
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Why does swapping require a temporary variable?
  2. What value do we use for foundIndex when the target is not found? Why is that useful?
  3. How is binary search different from linear search (in words, not code)?
  4. Why must the array be sorted for binary search?
  5. Which searching algorithm is required for the AP CSA exam?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete