AP Computer Science A: Lesson 4.5

Implementing Array Algorithms

Unit 4: Data Collections

This notebook serves as a complete lesson plan, presentation guide, live coding scratchpad, and homework lab for Topic 4.5.


🖥️ Presentation & Slide Deck

Slide 1: Standard 1D Array Patterns

  • Title: Standard 1D Array Traversal Algorithms
  • Key Patterns to Master:
    • Finding Minimum / Maximum values
    • Calculating Sums and Averages
    • Counting elements matching a condition
    • Shifting, rotating, and reversing elements

🗣️ Teacher Script:

“Array algorithms follow standard templates on the AP exam. Today we will focus on array mutation—specifically shifting elements without going out of bounds!”

Slide 2: Common Pitfalls & Live Code Tracing

Goal: Shift array elements left by 1 position (e.g., [10, 20, 30, 40] $\rightarrow$ [20, 30, 40, 10]).

Flawed Code (The Bug):

// Buggy Implementation - Live Demo
int[] arr = {10, 20, 30, 40};
for (int i = 0; i < arr.length; i++) {
    arr[i] = arr[i + 1]; // ArrayIndexOutOfBoundsException when i = arr.length - 1!
}

🗣️ Teacher Script:

“Look at what happens when i = arr.length - 1. When we evaluate arr[i + 1], Java attempts to access arr[4], which does not exist! To fix this, our loop bound must end at arr.length - 1, and we must save arr[0] beforehand.”

Slide 3: Corrected Implementation

// Corrected Shift Left Implementation
int[] arr = {10, 20, 30, 40};
int temp = arr[0]; // Save the first element

for (int i = 0; i < arr.length - 1; i++) {
    arr[i] = arr[i + 1]; // Shift remaining elements left
}
arr[arr.length - 1] = temp; // Place first element at the end

// Print result: [20, 30, 40, 10]


📄 Student Homework Assignment Handout

Title: Temperature Data Processor Lab

Instructions: Complete the static methods in the TemperatureAnalyzer class below using standard 1D array traversal algorithms.

public class TemperatureAnalyzer {

    /**
     * Counts how many times two consecutive days both had 
     * temperatures strictly greater than 90 degrees.
     */
    public static int countHeatWaves(int[] temps) {
        int count = 0;
        // TODO: Implement using a loop bound of temps.length - 1
        for (int i = 0; i < temps.length - 1; i++) {
            if (temps[i] > 90 && temps[i + 1] > 90) {
                count++;
            }
        }
        return count;
    }

    /**
     * Reverses the elements of the temps array in-place 
     * using a while loop and a swap mechanism.
     */
    public static void reverseLog(int[] temps) {
        int left = 0;
        int right = temps.length - 1;
        while (left < right) {
            int temp = temps[left];
            temps[left] = temps[right];
            temps[right] = temp;
            left++;
            right--;
        }
    }
}