0% found this document useful (0 votes)
49 views128 pages

Searching and Sorting Resources

The document outlines a project planning guide for creating a console program that demonstrates object-oriented programming and software engineering skills. Key requirements include using inheritance, method decomposition, data structures, and algorithms, along with documentation and optional features like user interaction. It also includes benchmarks for project progress, a rubric for assessment, and steps for brainstorming, user stories, and acceptance testing.

Uploaded by

henryszuster
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views128 pages

Searching and Sorting Resources

The document outlines a project planning guide for creating a console program that demonstrates object-oriented programming and software engineering skills. Key requirements include using inheritance, method decomposition, data structures, and algorithms, along with documentation and optional features like user interaction. It also includes benchmarks for project progress, a rubric for assessment, and steps for brainstorming, user stories, and acceptance testing.

Uploaded by

henryszuster
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

Searching and Sorting

Project Planning
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Creative Coding with the Console Project Planning Guide

For this project, you will create a program using the console that portrays a personal interest or solves a
problem that you choose. Your program should demonstrate the object-oriented programming and software
engineering skills and knowledge you have developed throughout the year.

Project Requirements
Use your knowledge of object-oriented programming, data structures, method decomposition, and algorithms
to create your program:

● Use inheritance and polymorphism – Create a superclass that represents shared attributes and
behaviors with at least two subclasses that are more specific versions or variations of the superclass.

● Method decomposition – Use overloaded, overridden, and private methods to implement different
versions of the same behavior, variations of a superclass behavior, and to improve code organization.

● Use at least two data structures – Use at least two 1D or 2D arrays or ArrayLists to store elements
that are manipulated using loops and conditionals.

● Implement one or more algorithms – Implement one or more algorithms that use loops and two-way
or multi-selection statements with compound Boolean expressions to analyze the data.

● Document your code – Use comments to explain the purpose of the methods and code segments and
note any preconditions and postconditions.

Optional Features
● Incorporate user interaction – Use methods in the Scanner class to obtain user input to interact with
your creative coding program.

● Use static variables, constants, and/or static methods – Use static variables to represent values
that are shared by all objects of a class, a constant to represent a value that doesn't change, and/or a
static method to represent a behavior that doesn't require an object or as a helper method.

● Use methods in the String class – Use one or more methods in the String class in your program,
such as to determine if a String contains specific characters or obtain a substring from a String.

● Use methods in the Math class – Use one or more methods in the Math class in your program, such
as to perform calculations on the values in a 2D array and display the results, choose random values
from the 2D array.

1
Project Benchmarks
Benchmark #1 Due Lesson 6
Brainstorm project ideas and goals

Decompose the problem to identify the classes and methods you will need
to implement

Obtain and implement feedback from peers

Benchmark #2 Due Lesson 8


Develop one or more classes and data structures

Implement one or more algorithms to create a visual or animation

Obtain and implement feedback from peers

Benchmark #3 Due End of Project


Self-assess your work using the program requirements and rubric

Finalize your program using the feedback you received and your
self-assessment

Showcase your work!

2
Project Rubric
Category Extensive Evidence Convincing Evidence Limited Evidence No Evidence

Inheritance and Creates a superclass and at Creates a superclass and one Creaets a superclass and a Does not create a superclass
Polymorphism least two subclasses that subclass that demonstrate subclass but does not use and subclass relationship.
demonstrate effective use of basic use of inheritance and these principles in meaningful
inheritance and polymorphism. or effective ways.
polymorphism.

Method Decomposition Writes multiple overloaded, Writes some overloaded, Writes some overloaded, Does not write any
overridden, and private overridden, and/or private overridden, and/or private overloaded, overridden, or
methods that effectively methods that implement methods, but their private methods.
implement different versions different versions of the same implementation is not
of the same behavior and behavior or variations of a effective or they do not
variations of a superclass superclass behavior, but the improve code organization.
behavior, resulting in code could be better
well-organized code. organized.

Data Structures Uses at least two 1D or 2D Uses at least one 1D or 2D Uses at least one 1D or 2D Does not use any 1D or 2D
arrays or ArrayLists that are array or ArrayList that is array or ArrayList, but it is arrays or ArrayLists.
effectively manipulated using effectively manipulated using not manipulated using loops
loops and conditionals. loops and conditionals. and conditionals.

Algorithms Implements more than one Implements one algorithm Implements one algorithm Does not implement an
algorithm using the data using a data structure. using a data structure but algorithm using a data
structures. does not loops and use structure.
AND two-way or multi-selection
AND statements with compound
The algorithm uses loops and Boolean expressions to
More than one algorithm uses two-way or multi-selection analyze the data and create
loops and two-way or statements with compound the visualization.
multi-selection statements Boolean expressions to
with compound Boolean analyze the data and create
expressions to analyze the the visualization.
data and create the
visualization.

3
Category Extensive Evidence Convincing Evidence Limited Evidence No Evidence

Documentation Uses single and multi-line Uses single-line comments to Uses single-line comments to Does not use comments to
comments to explain the explain the functionality and explain the functionality and document the functionality
functionality and purpose of purpose of methods and code purpose of methods in the and purpose of methods or
methods and code segments segments in the program program code segments in the
in the program program

4
Step 1: Breaking Down the Project
Identify Need to Knows
Consider what you already know and need to know to complete this project. Use these questions to guide and track your progress throughout the
unit and the project. Don't forget to add new questions to your Need to Know list as you learn more!

Know Need to Know Learned

5
Common Characteristics and Features
Review and analyze each of the project examples on Code Studio. As you review, use the box below to
generate a list of some common characteristics and key features that you see. This is simply an
investigation to see what you notice. We will cover some of the main project requirements throughout the
lessons of this unit.

6
Step 2: Brainstorming
For your project, you will choose a topic or problem you want to portray or address using the console.
Brainstorm ideas for things you are interested in or problems you want to address and ways that you want to
convey your topic with the console. For example:

● Option #1: Your business from the Store Management Project has expanded to multiple locations, and
you want to learn more about what makes each location uniquely successful! Create a program that
analyzes data across all your locations.

● Option #2: Expand your Data for Social Good Project to do more complex analysis. Model the data
using classes instead of primitive values.

● Option #3: Expand your Natural Language Processing Project to do more complex analysis. For
example, you want to find the most common word or the longest sentence in the text. Model the data
using classes instead of Strings.

● Option #4: Create a text based game.

● Option #5: Develop a program to keep track of items. For example, keep track of family recipes or
manage a To-Do list.

What personal interest do you want to portray or what problem do you want to address with your
program?

How do you want to convey your topic in a program using the console?

7
Step 3: User Stories
A user story is a short explanation of a program feature that is written from the end user's point of view to
describe how the feature will provide value to the user. User stories are often expressed in short sentences,
like "As a [persona], I [want to], [so that]." You should write a user story for each large step or component of
your overall project. For each user story:

● Identify the criteria for what it means for it to be considered "done".

● Decide which specific steps need to be completed for it to be considered "done".

User Story Criteria Steps to Complete

8
Step 4: Planning and Design
UML Diagrams

Create a UML diagram for your


class that will represent the scene
and any additional classes you
might need.

9
Step 5: Decompose the Problem
Class:

Method

Precondition(s)

Postcondition(s)

Pseudocode

10
Class:

Method

Precondition(s)

Postcondition(s)

Pseudocode

11
Step 6: Acceptance Testing
Test the acceptance criteria for your user stories. Your reviewer should test your program and determine which
of your user stories are complete and which ones still need work.

Criteria Passed Notes

12
Day 2: Software Engineers
How are you being a problem-solver while you are working on your project?

How are you being creative while you are working on your project?

13
End of Project Reflection
Describe your project.

What are two things about your project that you are proud of?

Describe something you would improve or do differently if you had an opportunity to change something about
your project.

14
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Project Planning

Check for Understanding

Consider the following method:

public String mystery(String myString, int index) {


if (index >= myString.length()) {
return myString;
}

return myString + mystery(myString.substring(index), index + 2);


}

What is printed as a result of executing the following line of code?

System.out.println(mystery("CSA is the best!", 0));

A. CSA is the best!

B. CSA is the best!CSA is the best!A is the best! the best!est!

C. CSA is the best! A is the best! The best! est! est!

D. CSA is the best!A is the best! The best!est!

E. CSA is the best!A is the best! The best!

1
AP Exam Prep

The following code segment is intended to return the location of a target element in an ArrayList.

public static int findLocation(ArrayList<Integer> numbers, int target) {


for (int index = 0; index < numbers.size(); index++) {
if (numbers.get(index) == target) {
return index;
}
}
return -1;
}

Which of the following conditions will cause the given code segment to not work as intended?

A. The ArrayList contains null elements.

B. The ArrayList is not sorted in ascending order.

C. The ArrayList contains duplicate elements.

D. The size of the ArrayList is less than the expected number of elements.

E. The ArrayList is not initialized with an initial capacity.

2
Extra Practice

Do This: Based on the system requirements below, create a prioritized list of the first 8 items needed to be
developed to create a chess game.

Chess Game System Requirements:

● The game is a two-player game.


● Each player is randomly assigned a color, black or white.
● The player assigned the color white plays the first move.
● Each player makes a move after their opposing player.
● The game is played on a checkered game board with 64 squares arranged in an 8×8 grid.
● Each side starts off with 8 pawns, 2 rooks, 2 bishops, 2 knights, 1 queen, and 1 king.
● The game can end in a checkmate from one side, forfeit, or resignation.
● All rules of international chess will be followed.

3
CSA Unit 8 Guide

Lesson 1: Project Planning


Reflection
Question of the Day: Why is it important to start a project by first identifying requirements, tasks, and
priorities?

What about this unit's project makes you excited? What parts of this project are you uncertain about?

1
Searching and Sorting
Searching
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - Counting Executions with Code

Linear Search - 1D Array


Use the following code segment to complete the following tables.

/* Uses linear search to find and return the location of findMe in arr
* @return -1 if findMe is not found
*/
public static int getLocation(String[] arr, String findMe) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(findMe)){
return i;
}
}
return -1;
}

Complete the table using the name from the first column to fill in the blank in the call to getLocation() using
the array declared below.

String[] friends = {"Tad", "Harume", "Joy", "Aurora", "Gloria"};


getLocation(friends, _______);

Name to search for Number of executions before


Best, Average, or Worst Case?
in friends getLocation() returns an answer

"Tad"

"Joy"

"Gloria"

"Brandon"

1
Complete the table using the name from the first column to fill in the blank in the call to getLocation() using
the array declared below.

String[] friends2 = {"Lisa", "Angela", "Pamela", "Renee", "Agnes", "Agatha", "Germaine",


"Jack", "Jolene"};
getLocation(friends, _______);

Name to search for Number of executions before


Best, Average, or Worst Case?
in friends getLocation() returns an answer

Best Case

Average Case

Worst Case

2
Linear Search - 2D Array
Use the following code segment to complete the following tables.

/* Uses linear search to find and return the location of name in arr
* @return true if name is in arr, otherwise false
*/
public static boolean containsName(String[][] arr, String name) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++){
if (name.equals(arr[row][col])){
return true;
}
}
}
return false;
}

Complete the table using the name from the first column to fill in the blank in the call to containsName() using
the array declared below.

String[][] seatingChart = {{"Cami", "Max", "Alicia"},


{null, "Sophia", "Val"},
{"Veronica", null, "Eric"}};

containsName(seatingChart, _______);

Name to search for Number of executions before


Best, Average, or Worst Case?
in seatingChart containsName() returns an answer

Best Case

Average Case

Worst Case

3
Challenge Questions
Consider a list of n items.

For any linear search, the best case will take __________ executions.

For a linear search over a list of length n, the worst case will take __________ executions.

For a linear search over a list of length n, the average case would take __________ executions.

4
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Searching

Check for Understanding

Consider the following code segment:

public int getLocation(int[] arr, int findMe) {


for (int i = 0; i < arr.length; i++) {
if (arr[i] == findMe){
return i;
}
}
return -1;
}

The following code segment appears in a different class.

int[] nums = /* missing code */;


int location = getLocation(nums, 86);

Which of the following replacements for /* missing code */ will cause the loop in the method to run the
maximum number of iterations (method runs in the worst case)?

I. {11, 28, 5, 25, 86}

II. {86, 25, 11, 5, 28}

III. {11, 25, 5, 99, 28}

A. I only

B. II only

C. III only

D. I and II only

E. I and III only

1
AP Exam Prep

The following method is intended to return the index of the location of target in the array arr, -1 otherwise:

public int find(String[] arr, String target) {


for (int i = arr.length - 1; i >= 0; i--) {
if (target.equals(arr[i])){
return i;
}
return -1;
}

return -1;
}

Which of the following best explains why the method does not work as intended?

A. There are two return statements that return -1.

B. It starts traversing at the end of the array.

C. When target is not the last element, it returns -1 instead of traversing the rest of the array.

D. The array index goes out of bounds.

E. There is no error; it works as intended.

2
Extra Practice

Do This: For each of the following scenarios, do you think it would be reasonable to use sequential/linear
search to find your target or would you hope there is a better way? Explain your answers.

Finding a specific page in a book.

Finding a specific picture of a friend in a stack of photos.

Finding the top result for a query using an internet search engine.

3
CSA Unit 8 Guide

Lesson 2: Searching
World's Worst Magician
How many guesses would the world’s best magician take?

How many guesses would the real world’s worst magician take?

Linear Search

Term Definition Example / Picture / Code

A search algorithm that checks each


linear/sequential item _______________________
search
until the target is found

1
CSA Unit 8 Guide

Term Definition Example / Picture / Code

The item is found on the very first


best case
attempt.

average case

The most number of executions an


worst case algorithm can take to complete its
goal.

What is the best case for the World's Worst Magician?

What is the average case for the World's Worst Magician?

What is the worst case for the World's Worst Magician?

2
CSA Unit 8 Guide

Counting Executions with Code

Term Definition Example / Picture / Code

execution count

Reflection
Question of the Day: How can I determine the efficiency of an algorithm?

We often use linear search in our daily lives to complete tasks. Think back to your past week and consider
where you have used it. What is the task, and how is linear search a valuable tool?

3
Searching and Sorting
Binary Search
Resources
Name(s) _____________________________________________________________________ Period ____________ Date ______________________________

Activity Guide - Binary Search

Binary Search Algorithm


Write the pseudocode for the binary search algorithm.

1
Test Your Algorithm
Use the cards to test your algorithm. Modify your algorithm until it correctly locates the card.

⬜ Can your algorithm find the 4?


µ Can your algorithm find the 2?
µ Can your algorithm find the 7?
µ Can your algorithm find the 8?

What is special about the ordering of the cards?

Would your algorithm work if the cards were in a different order? Try it out!

2
Predict Execution Counts
Given the worst case linear search execution counts, complete the table with your prediction of the worst case execution counts of your new
algorithm given the length of the array int[] arr.

arr.length Worst case linear search execution count Worst case execution count for new algorithm

1 1

3 3

5 5

9 9

3
Option A
Part 1: Trace the Code

Use your cards to correspond to the values in the array and walk through the code segment.

1 int[] arr = {2, 4, 5};


2 int left = 0;
3 int right = arr.length - 1;
4 int target = 2;
5 int executionCount = 0;
6 while (left <= right) {
7 executionCount++;
8 int mid = (left + right) / 2;
9 if (arr[mid] < target) {
10 left = mid + 1;
11 }
12 else if (arr[mid] > target) {
13 right = mid - 1;
14 }
15 else {
16 return mid;
17 }
18 }
19 return -1;

4
Part 2: Create a Trace Table

Create a trace table to trace the algorithm step by step. What value does it return?

5
Option B
Part 1: Trace the Code

Use your cards to correspond to the values in the array and walk through the code segment.

1 int[] arr = {2, 4, 5, 7, 8};


2 int left = 0;
3 int right = arr.length - 1;
4 int target = 2;
5 int executionCount = 0;
6 while (left <= right) {
7 executionCount++;
8 int mid = (left + right) / 2;
9 if (arr[mid] < target) {
10 left = mid + 1;
11 }
12 else if (arr[mid] > target) {
13 right = mid - 1;
14 }
15 else {
16 return mid;
17 }
18 }
19 return -1;

6
Part 2: Create a Trace Table

Create a trace table to trace the algorithm step by step. What value does it return?

7
Option C
Part 1: Trace the Code

Use your cards to correspond to the values in the array and walk through the code segment.

1 int[] arr = {2, 4, 5, 7, 8, 9, 11, 13, 14};


2 int left = 0;
3 int right = arr.length - 1;
4 int target = 2;
5 int executionCount = 0;
6 while (left <= right) {
7 executionCount++;
8 int mid = (left + right) / 2;
9 if (arr[mid] < target) {
10 left = mid + 1;
11 }
12 else if (arr[mid] > target) {
13 right = mid - 1;
14 }
15 else {
16 return mid;
17 }
18 }
19 return -1;

8
Part 2: Create a Trace Table

Create a trace table to trace the algorithm step by step. What value does it return?

9
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Binary Search

Check for Understanding

Suppose the binarySearch method is called with an array containing 10 elements sorted in increasing order.
What is the maximum number of times that the statement indicated by /* calculate midpoint */ could
execute?

public static int binarySearch(int[] a, int target) {


int left = 0;
int right = a.length - 1;
while (left <= right) {
int mid = (left + right) / 2; /* calculate midpoint */
if (a[mid] < target) {
left = mid + 1;
}
else if (a[mid] > target) {
right = mid - 1;
}
else {
return mid;
}
}
return -1;
}

A. 4

B. 5

C. 9

D. 10

E. 11

1
AP Exam Prep

Consider the following binarySearch method that appears in a class Searcher.

public static int binarySearch(int[] a, int target) {


int left = 0;
int right = a.length - 1;
while (left <= right) {
int mid = (left + right) / 2; /* calculate midpoint */
if (a[mid] < target) {
left = mid + 1;
}
else if (a[mid] > target) {
right = mid - 1;
}
else {
return mid;
}
}
return -1;
}

The following code segment appears in a different class.

int[] arr = {1, 3, 5, 7, 9};


System.out.println(Searcher.binarySearch(arr, 5);

What will be output when this code segment is executed?

A. -1

B. 0

C. 1

D. 2

E. 3

2
Extra Practice

Do This: There is a bug in this binarySearch. Find parameters that will not return the correct answer, and
describe the fix to the bug.

1 public static int binarySearch(int[] arr, int target) {


2 int left = 0;
3 int right = arr.length - 1;
4 while (left <= right) {
5 int mid = (left + right) / 2; /* calculate midpoint */
6 if (a[mid] < target) {
7 left = mid + 1;
7 }
9 if (a[mid] > target) {
10 right = mid - 1;
11 }
12 else {
13 return mid;
14 }
15 }
16 return -1;
17 }

3
CSA Unit 8 Guide

Lesson 3: Binary Search


World's Not as Bad Magician
What would the worst case execution count be if we used a linear search to find a specific card?

What if this was the deck we needed to search?

Binary Search

Term Definition Example / Picture / Code

binary search

1
CSA Unit 8 Guide

How does increasing the length of the array impact the execution count?

How does the execution counts for the binary search algorithm compare to the execution counts for the linear
search algorithm?

2
CSA Unit 8 Guide

Recursive Binary Search


Annotate the code below.

public static int binarySearch(int[] arr, int low, int high, int target) {

if (high < low) {

return -1;

int mid = (low + high) / 2;

if (arr[mid] == target) {

return mid;

if (arr[mid] > target) {

return binarySearch(arr, low, mid - 1, target);

else {

return binarySearch(arr, mid + 1, high, target);

Base Case #1 Base Case #2

Recursive Step

3
CSA Unit 8 Guide

Reflection
Question of the Day: How is a binary search more efficient than a linear search?

What is one benefit and one limitation of the binary search algorithm?

4
Searching and Sorting
Selection Sort
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - Selection Sort

Instructions
Step 1: Place the five cups upside down on a desk or table.

1. Place the sticky note with the Index 0 written in front of the left-most upside-down cup.
2. Choose one person in your group to be the sorter who will pick up the cups. Pick a recorder who will
update the index on the sticky note.
3. The rest of the group will direct the sorter on which cup has the smaller number and which cups should
be swapped to sort the numbers in ascending order.
4. Use the pseudocode on the slide to assist you with following the selection sort algorithm.

Step 2: The sorter picks the cup up at index 0 with their left hand, places the number on the outside of the cup,
shows the number to the group, and keeps the cup in their hand.

Step 3: The sorter picks up the left-most upside-down cup with their right hand, places the number on the
outside of the cup, shows the number to the group, and keeps the cup in their hand.

Step 4: The group decides which number is smaller.

Step 5: If the number on the cup in the sorter’s right hand is smaller, tell the recorder to cross out the index on
the sticky note and write the index of the cup in the right hand.

1. Tell the sorter to place both cups right side up on the table.
2. Tell the recorder to place the updated sticky note in front of the cup with the smaller number.
3. Repeat the process in Step 2 with the new index.

Step 6: If the cup in the right hand is not smaller, tell the sorter to place both cups back right side up. Repeat
the process in Step 2 starting with the second left-most cup.

Step 7: After you have gone through the entire array of cups, swap the cup with the index sticky note with the
cup you started at.

Step 8: Repeat the process by starting with the cup at index 2 and updating the sticky note with the starting
index. Increase the index and update the sticky note each time you make it to this step until all cups have been
sorted.

Step 9: Congratulations, your group used a selection sort to place random numbers in order! 🎉

1
Runtime Efficiency Analysis
How many times does it take you to swap the numbers to place them in order?

For an array containing the values [32, 44, 13, 17], what is the number of iterations performed after all
swaps have been made?

If numbers were sorted in ascending order, would it change the runtime in the selection sort? Why or why not?
If you are unsure, try it out with the numbers placed on your cups.

2
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Selection Sort

Check for Understanding

Consider the following sort method. This method correctly sorts the elements of array data into increasing
order.

public static void selectSort(int[] arr) {


for (int index = 0; index < data.length - 1; index++) {
int current = index;
for (int next = index + 1; next < data.length; next++) {
if (data[next] < data[current]) { // Compare values
current = next;
}
}
int temp = data[current]; // Assign to temp
data[current] = data[index];
data[next] = temp;
} // End of outer loop
}

Assume that selectSort is called with the array {16, 13, 12, 50, 40, 10}. What will the value of data be
after three passes of the outer loop (i.e., when j = 2 at the point indicated by /* End of outer loop */) ?

A. {10, 12, 12, 50, 40, 10}

B. {10, 12, 13, 16, 40, 50}

C. {10, 13, 12, 50, 40, 16}

D. {10, 12, 13, 50, 40, 10}

E. {10, 12, 13, 50, 40, 16}

1
AP Exam Prep

Consider the following implementation of the selection sort algorithm.

1 public static void selectSort(int[] elements) {


2 for (int index = 0; index < elements.length - 1; index++) {
3 int minIndex = index;
4 for (int next = index + 1; next < elements.length; next++) {
5 if (elements[next] < elements[minIndex]) {
6 minIndex = next; // Line 11
7 }
7 }
9 if (next != minIndex) {
10 int temp = elements[index];
11 elements[next] = elements[minIndex];
12 elements[minIndex] = temp;
13 }
14 }
15 }

The following declaration and method call appears in the same class as selectSort.

int[] vals = {5, 10, 2, 1, 12};


selectSort(vals);

How many times is the statement minIndex = k; on Line 11 of the method executed as a result of the call to
selectSort?

A. 0

B. 1

C. 2

D. 3

E. 4

2
Extra Practice

Do This: Given the following array arr[] = 64 25 12 22 11:

1. Use selection sort to place the given array in ascending order.


2. Write comments explaining each iteration.

3
CSA Unit 8 Guide

Lesson 4: Selection Sort


Sorting Data
How do you think websites like Amazon perform these sorts?

Selection Sort

Term Definition Example / Picture / Code

selection sort

Add comments and annotate the pseudocode below.

set min to location 0

search for the smallest value in the list

swap with value at location min

increment min to point to next element

repeat until list is sorted

1
CSA Unit 8 Guide

When would the selection sort algorithm be useful in our programs?

What are some limitations or issues with using the selection sort algorithm?

Reflection
Question of the Day: How can I sort elements in a data structure?

How did your engagement in class content impact your learning today?

2
Searching and Sorting
Insertion Sort
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - Project Planning Feedback

Feedback Process
Step 1: Partner A presents their project idea. Partner B listens.

Step 2: Partner A asks for specific feedback on a certain area of the project (the framing question).

Step 3: Partner B gives feedback. Partner A listens and takes notes.

Step 4: Open discussion between partners about the suggestions and feedback.

Step 5: Partner A thanks Partner B for their feedback. Switch roles to repeat the process.

Framing Question
What can I make better about . . .? How can I improve . . .?

1
Feedback Notes

Based on your self-assessment and progress, what actionable commitments can you make to improve your
process moving forward?

2
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - Sorting Comparison

Using the code segments below, compare the efficiency of selection sort and insertion sort by counting the
number of comparisons needed to sort a given list. For each of the three examples below:

1. Create a single list of five numbers.


2. Sort it using both algorithms. As you sort, count the number of comparisons that are made between
elements (i.e., one number in the list is greater than another number in the list).
3. Share the total number of comparisons for each initial condition to indicate efficiency.

for (int j = 0; j < data.length - 1; j++) {


int m = j;
for (int k = j + 1; k < data.length; k++) {
// Compare values
if (data[k] < data[m]) {
m = k;
Selection
}
Sort
}

int temp = data[m];


data[m] = data[j];
data[j] = temp;
}

for (int i = 1; i < data.length; i ++) {


int temp = data[i];
int index = i;
// Compare values
while (index > 0 && data[index - 1] > temp) {
Insertion
data[index] = data[index - 1];
Sort
index --;
}

data[index] = temp;
}

1
Randomized List
Choose five numbers in a random order. List them here:

, , , ,
Use the workspace below to sort your numbers, counting the number of comparisons that are made.

Selection
Sort

Total Comparisons

Insertion
Sort

Total Comparisons

2
Reversed List
Choose five numbers in reverse order (largest to smallest). List them here:

, , , ,
Use the workspace below to sort your numbers, counting the number of comparisons that are made.

Selection
Sort

Total Comparisons

Insertion
Sort

Total Comparisons

3
Sorted List
Choose five numbers that are already in sorted order (smallest to largest). List them here:

, , , ,
Use the workspace below to sort your numbers, counting the number of comparisons that are made.

Selection
Sort

Total Comparisons

Insertion
Sort

Total Comparisons

4
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Insertion Sort

Check for Understanding

Consider the following two statements about insertion sort:

I. After k iterations through the outside loop, the first k elements are sorted.
II. After k iterations through the outside loop, the first k elements are the smallest elements in the list.

Which of these statements are true?

A. Statement I and II are both true

B. Statement I is true, and statement II is false

C. Statement I is false, and statement II is true

D. Statements I and II are both false

AP Exam Prep

Complete the code segment below by adding the missing code to correctly implement insertion sort.

public static void insertionSort(String[] nums) {


for (int i = 1; i < nums.length; i++) {
int temp = nums[i];
int index = i - 1;
while (/* missing code */) {
nums[index + 1] = nums[index];
index--;
}
nums[index + 1] = temp;
}
}

1
Extra Practice

Do This: For each of the arrays provided, determine its state after the specified number of iterations of
insertion sort.

{2, 3, 7, 1, 9, 8}

after four iterations

{"puppy", "dog", "cat", "giraffe"}

after two iterations

{2, 5, 9, 10}

after three iterations

{4, 7, 72, 9, 1, 9, 7}

after five iterations

{"apple", "peach, "banana", "strawberry"}

after three iterations

2
CSA Unit 8 Guide

Lesson 5: Insertion Sort


Insertion Sort

Term Definition Example / Picture / Code

insertion sort

Add comments and annotate the pseudocode below.

loop list from index 1 to the end of the list

set current to the value at index

set next to the value at index - 1

while next is greater than or equal to 0 and the value at next is greater than current

set the element at next + 1 to the value at next

decrement next

set the element at next + 1 to current

What qualities are important when deciding whether one algorithm is better than another?

1
CSA Unit 8 Guide

Comparing Sorting Algorithms


Which algorithm is best when we consider efficiency?

Which algorithm is best when we consider readability?

Which algorithm is best when we consider ease of programming?

2
CSA Unit 8 Guide

Reflection
Question of the Day: How does the insertion sort algorithm compare in efficiency with the selection sort
algorithm?

Complete the following sentences:

Insertion sort is similar to selection sort but

Insertion sort is similar to selection sort because

Insertion sort is similar to selection sort so

3
Searching and Sorting
Merge Sort
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - Merge Sort

Fill in the following diagram, which represents a top-down view of the merge sort algorithm used to sort the
array containing the values [5, 4, 12, 25, 10, 24, 1, 19].

How many times did the algorithm merge the sub-arrays?

What were the last two arrays that were merged?

In your own words, describe how merge sort works.

1
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Merge Sort

Check for Understanding

Consider the following code segment, which appears in a method in the same class as mergeSortHelper and
merge.

int[] numbers = {18, 4, 8, 11};


int[] temp = new int[numbers.length];
mergeSortHelper(numbers, 0, numbers.length - 1, temp);

How many times will the merge method be called as a result of executing the code segment?

A. 1

B. 2

C. 3

D. 4

E. 5

1
AP Exam Prep

Consider the following code segment, which appears in a method in the same class as mergeSortHelper and
merge.

int[] vals = {28, 25, 23, 20, 26, 27};


int[] temp = new int[vals.length];
mergeSortHelper(vals, 0, vals.length - 1, temp);

Which of the following represents the arrays merged the last time the merge method is executed as a result of
the code segment above?

A. {20, 23, 25} and {26, 27, 28} are merged to form {20, 23, 25, 26, 27, 28}.

B. {20, 25, 27} and {23, 26, 28} are merged to form {20, 23, 25, 26, 27, 28}.

C. {20, 25, 27} and {23, 26, 28} are merged to form {20, 25, 27, 23, 26, 28}.

D. {23, 25, 28} and {20, 26, 27} are merged to form {20, 23, 25, 26, 27, 28}.

E. {23, 25, 28} and {20, 26, 27} are merged to form {23, 25, 28, 20, 26, 27}.

Extra Practice

Do This: Create an unsorted array of integers of length 8, then draw the merge sort diagram for it.

2
CSA Unit 8 Guide

Lesson 6: Merge Sort


Counting Loose Change
Brainstorm an algorithm for counting loose change.

Term Definition Example / Picture / Code

A group of chefs in a restaurant


each complete individual tasks to
divide-and-conquer
make portions of a meal that is
presented to a customer.

1
CSA Unit 8 Guide

How do you think sorting algorithms can use a divide-and-conquer approach?

Merge Sort

Term Definition Example / Picture / Code

merge sort

helper method

2
CSA Unit 8 Guide

public static void sort(int[] numList, int left, int right) {

if (left < right) {

int middle = (left + right) / 2;

sort(numList, left, middle);

sort(numList, middle + 1, right);

merge(numList, left, middle, right);

What are the base cases?

What is the recursive call?

3
CSA Unit 8 Guide

Reflection
Question of the Day: How does the merge sort algorithm compare in efficiency with the selection and
insertion sort algorithms?

We have now spent three lessons thinking about sorting algorithms. What are two big takeaways that you have
about sorting and programming?

4
Searching and Sorting
Searching and Sorting
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Searching and Sorting

Check for Understanding

Consider the following code segment:

ArrayList<String> menuItems = new ArrayList<String>();


menuItems.add("Curry");
menuItems.add("Stir Fry");
menuItems.add("Noodles");
menuItems.add("Fried Rice");

ArrayList<Double> prices = new ArrayList<Double>();


prices.add(13.50);
prices.add(12.00);
prices.add(13.00);
prices.add(14.00);

public String[] withinBudget


(ArrayList<String> menu, ArrayList<double> prices, double budget) {
ArrayList<String> choices = new ArrayList<String>();
for (int i = 0; i < menu.size(); i++) {
if ( /* missing code 1 */ ) {
/* missing code 2 */
}
}

return choices;
}

Which two code segments can be inserted in for /* missing code 1 */ and /* missing code 2 */ in
order to return a list of menu items that are equal to or below the budget?

A. prices.get(i) == budget, choices.add(menu.get(i));

B. prices.get(i) <= budget, choices.add(menu.get(i));

C. prices.get(i) <= budget, menu.add(menu.get(i));

D. menu.get(i) <= budget, choices.add(prices.get(i));

E. menu.get(i) == budget, choices.add(prices.get(i));

1
AP Exam Prep

Your city is hosting a charity marathon that will occur on two different dates and stores the names of registered
participants in two ArrayLists of String objects called day1Runners and day2Runners. Interested
participants could register for one or both of the dates. When a participant registers, their name is added to
either the day1Runners list, the day2Runners list, or both.

The city wants a new list created containing the names of all unique participants that have registered for either
or both dates of the marathon. Write pseudocode or Java code to merge the two lists into one new list without
any duplicates.

2
Extra Practice

Do This: You have implemented standard algorithms that utiliz e array traver sal to determine if multiple
elements have a particular property. Let's use this algorithm to check a word for the game of Wordle, and
update each character's color property.

Assume the class Letter has already been defined, and is described by this UML diagram:

Letter

- letter: String
- color: String

+ getLetter()
+ getColor()
+ setColor(String color)

Implement updateColor(Letter[] guess, Letter[] goal) which accepts a guess word and a goal word,
then changes the letter property of the goal word based on the following rules:

● Green: The character is in the word and in the correct location.


● Yellow: The character is part of the word, but not in the correct lo
cation.
● Gray: The character is not part of the word.

Assume that guess and goal are the same length.

public void updateColor(Letter[] guess, Letter[] goal) {

3
CSA Unit 8 Guide

Lesson 7: Searching and Sorting


Creating a Playlist
Brainstorm an algorithm for how to combine two playlists into one single list.

Searching Algorithms
How does the linear search algorithm work?

How does the binary search algorithm work?

Which is more efficient? Why?

1
CSA Unit 8 Guide

When is the binary search algorithm not the most efficient?

Sorting Algorithms
How does the selection sort algorithm work?

How does the insertion sort algorithm work?

How does the merge sort algorithm work?

Which is more efficient? Why?

2
CSA Unit 8 Guide

Reflection
Question of the Day: How can I implement searching and sorting algorithms when working multiple lists?

How might our program differ if we are traversing 1D arrays vs ArrayLists?

3
Searching and Sorting
Project Development
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Project Development

Check for Understanding

What is always true about applying binary search on an array?

A. The array must be sorted.

B. Binary search is always faster than linear search, no matter what element you are searching for.

C. Cannot use merge sort before to sort the list being searched.

D. Must use insertion sort before to sort the list being searched.

E. The array cannot be sorted.

1
AP Exam Prep

Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of
integers.

/** Precondition: (arr.length == 0 or 0 <= from <= to <= arr.length)


* arr.length == temp.length
*/
public static void mergeSortHelper(int[] arr,int from, int to, int[] temp) {
if (from < to) {
int middle = (from + to) / 2;
mergeSortHelper(arr, from, middle, temp);
mergeSortHelper(arr, middle + 1, to, temp);
merge(arr, from, middle, to, temp);
}
}

The merge method is used to merge two halves of an array (arr[ from]through arr[ middle] , inclusive, and
arr[ middle + 1through
] arr[ to], inclusive) when each half has already been sorted into ascending order.

For example, consider the array arr1, which contains the values { 1 , 3 , 5 , 7 , 2 .,The 4 lower
, 6 half
, 8 }
of arr1 is sorted in ascending order (elements arr1 [ 0through
] arr1 [ ,3or] { 1 , 3 , ),
5 as
, is7the
} upper
half of arr1 (elements arr1 [ 4through
] arr1 [ ,7or] { 2 , 4 , ).6 , 8 }

The array will contain the values { 1 , 2 , 3 , 4 , 5 ,after 6 the


, method
7 , 8 call
} merge( arr1 , 0 , 3 ,
. The array temp is a temporary array declared in the calling program.
7 , temp)

Consider the following code segment, which appears in a method in the same class as mergeSortHelper and
merge.

int[] numbers = {100, 25, 50, 75};


int[] temp = new int[numbers.length];
mergeSortHelper(numbers, 0, numbers.length - 1, temp);

How many times will the merge method be called as a result of executing the code segment?

A. 1

B. 2

C. 3

D. 4

E. 5

2
Extra Practice

Do This: Why would you choose insertion vs selection sort?

3
Searching and Sorting
Privacy and Security
Resources
CSA Unit 8 Study Guide

Unit 8: Searching and Sorting


This unit expands on algorithms students have learned to introduce common approaches to searching and
sorting 1D and 2D arrays and ArrayLists. In the process, students analyze and compare the efficiencies of
these algorithms using statement execution counts and further develop problem-solving skills to decompose
complex problems. Throughout the unit, students apply their programming and software engineering skills to
plan and develop a creative coding project using the console that incorporates object-oriented design, data
structures, and algorithmic thinking. You also have the opportunity to consider the privacy and security of
programs and users.

Objectives
In this unit, you learned:

● Explain the functionality of the standard searching and sorting algorithms

● Analyze the efficiency of searching and sorting algorithms using execution counts

● Implement algorithms involving multiple 1D or 2D arrays or ArrayLists

1
Lesson 2: Searching
How can I determine the efficiency of an algorithm?

You have learned and practiced implementing standard algorithms to find a target element in a list throughout
the year. In this lesson, you realize that you have been using the linear search algorithm to find elements and
review how this algorithm is applied to different data structures. You learn how to use execution counts to
determine the best, average, and worst cases and practice evaluating the linear search algorithm to determine
its efficiency. You then write user stories for your Creative Coding with the Console Project to identify required
program features.

Key Terms

Term Definition

average case the average number of executions an algorithm can take to complete its goal

best case the least number of executions an algorithm can take to complete its goal

execution count the number of times a code segment runs

linear/sequential search a search algorithm that checks each item in order until the target is found

worst case the most number of executions an algorithm can take to complete its goal

Syntax

for (int index = 0; index < myList.length; index++) {


if (myList[index] == target) {
// code to execute
}
}

2
Lesson 3: Binary Search
How is a binary search more efficient than a linear search?

You previously learned how to evaluate the linear search algorithm to determine its efficiency using execution
counts and identified limitations of this approach to searching. In this lesson, you discover a better searching
algorithm that can perform more efficiently if the list is already sorted. You explore the binary search algorithm
to evaluate its efficiency and compare it to the linear search. You also revisit recursion and explore how the
binary search algorithm can be implemented recursively.

Key Terms

Term Definition

a search algorithm that finds a target element in a sorted list by dividing the list
binary search
in half in each iteration

Syntax

public int binarySearch(int[] myList, int target) {


int low = 0;
int high = myList.length - 1;

while (low <= high) {


int mid = low + (high - 1) / 2;

if (myList[mid] == target) {
return mid;
}
else if (myList[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}

return -1;
}

3
public int recursiveBinary(int[] myList, int low, int high, int target) {
if (high >= 1) {
int mid = low + (high - 1) / 2;

if (myList[mid] == target) {
return mid;
}
else if (myList[mid] > target) {
return recursiveBinary(myList, low, mid - 1, target);
}
else {
return recursiveBinary(myList, mid + 1, high, target);
}
}

return -1;
}

4
Lesson 4: Selection Sort
How can I sort elements in a data structure?

In this lesson, you learn about the selection sort algorithm. After investigating a program using the selection
sort algorithm to sort a list of values, you explore its functionality using manipulatives and evaluate its efficiency
using execution counts. You then identify the benefits and limitations of the selection sort algorithm and
scenarios where a selection sort would be useful to sort a list of values.

Key Terms

Term Definition

a sorting algorithm that selects the smallest element from an unsorted array in
selection sort
each iteration and places that element at the beginning of the unsorted array

Syntax

public void selectionSort(int[] myList) {


for (int i = 0; i < myList.length - 1; i++) {
int index = i;

for (int j = i + 1; j < myList.length; j++) {


if (myList[j] < myList[index]) {
index = j;
}
}

int smallerNumber = myList[index];


myList[index] = myList[i];
myList[i] = smallerNumber;
}
}

5
Lesson 5: Insertion Sort
How does the insertion sort algorithm compare in efficiency with the selection sort algorithm?

You previously learned about the selection sort algorithm and evaluated its functionality and limitations. In this
lesson, you explore the insertion sort algorithm and compare its functionality and efficiency with the selection
sort algorithm. You analyze the efficiency of each algorithm using execution counts and identify the benefits
and limitations of both the selection and insertion sort algorithms.

Key Terms

Term Definition

a sorting algorithm that shifts each item in a list one at a time to the correct
insertion sort
position in the sorted portion of the list

Syntax

public void insertionSort(int[] myList) {


for (int index = 1; index < myList.length; index++) {
int current = myList[index];
int newPosition = index - 1;

while ((newPosition >= 0) && (myList[index] > current)) {


myList[newPosition + 1] = myList[newPosition];
newPosition--;
}

myList[newPosition + 1] = current;
}
}

6
Lesson 6: Merge Sort
How does the merge sort algorithm compare in efficiency with the selection and insertion sort
algorithms?

You explore the merge sort algorithm to organize elements in a list using a divide-and-conquer approach and
identify the components of the algorithm. You learn how the algorithm uses helper functions to implement the
divide-and-conquer approach and practice tracing the algorithm to understand its functionality. You determine
its efficiency using execution counts and compare it with the insertion and selection sort algorithms.

Key Terms

Term Definition

the process of dividing a problem into smaller problems, solving the smaller
divide-and-conquer problems independently, then combining the solutions to solve the original
problem

helper function a function that performs a component of another function

a divide-and-conquer sorting algorithm that repeatedly breaks down a list into


merge sort sublists until each sublist consists of a single element and merges those sorted
sublists until it results into a sorted list

7
Syntax

public void merge(int[] leftList, int[] rightList, int[] myList, int left, int right) {

int index = 0;
int leftIndex=0;
int rightIndex = 0;

while(leftIndex < left && rightIndex < right) {


if (leftList[leftIndex] < rightList[rightIndex]) {
myList[index++] = leftList[leftIndex++);
}
else {
myList[index++] = leftList[leftIndex++);
}
}

while (leftIndex < left) {


myList[index++] = leftList[leftIndex++];
}

while (rightIndex < right) {


myList[index++] = rightList[rightIndex++];
}
}

public void mergeSort(int[] myList, int length) {


if (length < 2) {
return;
}

int mid = length / 2;


int[] leftList = new int[mid];
int[] rightList = new int[length - mid];

int k = 0;
for (int index = 0; index < length; ++index) {
if (index < mid) {
leftList[index] = myList[index];
}
else {
rightList[k] = myList[index];
k = k + 1;
}
}

mergeSort(leftList, mid);
mergeSort(rightList, length - mid);
merge(leftList, rightList, myList, mid, length - mid);
}

8
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - Data, Privacy, and Security

Think from the perspective of a software engineer. For the data collected in each of the scenarios - Home,
School, and Hobbies, what can you do with that data? What are the risks of collecting that data?

Excerpts
Partner A should read Excerpt A and answer the questions. Partner B should read Excerpt B and answer the
questions. If you finish before your partner, start reading the other excerpt. Then, share with your partner what
you learned.

Excerpt A

Excerpted from the New York Times article "Uber Agrees to Privacy Audits in Settlement With F.T.C."

Uber has agreed to two decades of privacy and security audits to settle federal accusations that it did not keep promises
to protect customer data.

The Federal Trade Commission announced the settlement with Uber, a ride-sharing company, on Tuesday, ending an
investigation that began in 2014 when the company promised to strengthen its privacy and security. The promises were
made after a public outcry over reports that Uber employees were peering into the travel logs of customers.

The company will not face financial penalties from the deal, its second settlement with the commission this year. In
January, Uber agreed to pay the commission $20 million over accusations that it deceived drivers by exaggerating
potential earnings. The company has also been under investigation by the Department of Justice on suspicion of using a
tool to evade law enforcement.

“This case shows that, even if you’re a fast growing company, you can’t leave consumers behind: you must honor your
privacy and security promises,” said Maureen K. Ohlhausen, the acting chairwoman of the F.T.C.

In the privacy case, the F.T.C. accused Uber of two violations. The first stemmed from the company’s announcement in
2014 that it had developed an automated system to monitor employee access to consumer personal information.

The extra privacy measures were announced in response to news reports that some Uber employees were using a tool
known as “God View” to track trips taken by users. On its website and in a statement, Uber announced that it had “a strict
policy prohibiting all employees at every level from accessing a rider or driver’s data.” It said, “The only exception to this
policy is for a limited set of legitimate business purposes.”

But the commission said it found that the company did not live up to that promise. In its complaint, the commission said
that Uber stopped using its automated system of monitoring employee access to information less than a year after it was
announced and that when it was in place, the company rarely monitored it.

“The system was not designed or staffed to effectively handle ongoing review of access to data,” the commission said.

1
Excerpt A Questions

What were the impacts on personal privacy and security?

What was the cause?

Compare this scenario to the Open Source Bugs. What are the differences?

When your partner has finished reading their excerpt, share with them what you learned.

2
Excerpt B

Excerpted from the Vice article "Sources: Facebook Has Fired Multiple Employees for Snooping on Users"

On Tuesday, Facebook fired an employee who had allegedly used their privileged data access to stalk women online.
Now, multiple former Facebook employees and people familiar with the company describe to Motherboard parts of the
social media giant’s data access policies. This includes how those in the security team, which the fired employee was
allegedly a part of, have less oversight on their access than others.

The news emphasizes something that typical users may forget when scrolling through a Silicon Valley company’s service
or site: although safeguards against abuse may be in place, there are people who have the power to see information you
believe to be private, and sometimes they may look at that data.

Motherboard granted the sources in this story anonymity to speak more candidly about Facebook’s policies and
procedures. One source specifically mentioned Facebook’s strict non-disclosure agreement.

One former Facebook worker said when they joined the company multiple people had been terminated for abusing access
to user data, including for stalking exes.

Another former Facebook employee said that they know of three cases where people were fired because they mishandled
data, one of which included stalking. Typically, these incidents are not publicly reported.

As with many other businesses, data access is distributed depending on an employee’s role in a company. One source
familiar with Facebook employees’ data access told Motherboard that different teams have varying levels of access, and
that they can request additional access if required. The person added that the security team is more trusted than other
departments, and abuse there is more difficult to detect. The employee Facebook recently fired for allegedly stalking
women was a security engineer, according to Jackie Stokes, founder of Spyglass Security, who originally flagged the case
earlier this week. Engineers are trained specifically on data access policies when they join the company, according to
Facebook.

Several sources did not specify the sort of data that different types of Facebook employees could access (such as
whether certain Facebook employees can read private messages or "friends only" wall posts.) But in 2015, a Finnish
music producer and DJ visited Facebook’s L.A. campus and watched as an engineer accessed his Facebook account
without a password. In March, a Facebook employee told The Guardian “When you first get to Facebook you are shocked
at the level of transparency. You are trusted with a lot of stuff you don’t need access to.”

It’s not only full time staff who can access some non-public user data. Although certainly not the most sensitive data
potentially available to workers, a former contractor explained to Motherboard how they were able to see which users
were the administrators of Facebook Pages. While employed by Facebook, the contractor showed Motherboard he could
access this data seemingly for any page by providing non-public data for several test pages Motherboard controlled.

Facebook data is not a free-for-all though, with employees just able to grab whatever they desire without consequence,
according to one of the former employees. When accessing non-public information about a particular user—including a
log of a user’s activity—the former employee faced a pop-up asking if they were authorised to view the data and whether
they were using the tool for work purposes. The source emphasized that their access was nothing special for a Facebook
employee at that time. When a worker attempts to access sensitive data, they see a warning that reminds the worker of
Facebook's policies, and which requires them to confirm they need the requested access, according to Facebook. The
social network also has automated systems in place designed to detect and prevent any abuse, Facebook said.

“They make it very clear to you: if you go one step too far, you’ll have big problems,” the former employee told
Motherboard. Multiple sources praised the security mechanisms in place.

In a statement provided to Motherboard Tuesday, Alex Stamos, Facebook’s chief information security officer, said
“Employees who abuse these controls will be fired.”

3
“It’s important that people’s information is kept secure and private when they use Facebook. It’s why we have strict policy
controls and technical restrictions so employees only access the data they need to do their jobs—for example to fix bugs,
manage customer support issues or respond to valid legal requests,” Stamos said.

Facebook declined to answer a list of specific questions on how many or what percentage of employees have access to
sensitive user data.

Excerpt B Questions

What were the impacts on personal privacy and security?

What was the cause?

Compare this scenario to the Open Source Bugs. What are the differences?

When your partner has finished reading their excerpt, share with them what you learned.

4
Name(s) __________________________________________________ Period _______ Date _____________________

Extra Practice - Privacy and Security

Check for Understanding

In 2017, Equifax was breached by hackers who retrieved hundreds of millions of customer records. This was
able to occur because a vulnerability had been identified, but was not patched quickly. Additionally, once the
attackers hacked the initial firewall, there was no additional protection, allowing them to freely navigate inside
the system. Finally, database content was given to all 'trusted' users rather than only those who needed the
information. Which of the following secure design principles was not compromised prior to the attack?

A. Complete Mediation - Every access to every object must be checked for authorization

B. Least Privilege - Every program and every user of the system should operate using the least set of
privileges necessary to complete the job

C. Economy of Mechanism - Keep the design of the system as simple as possible

D. Design for Updates - Developers should plan for the safe and reliable installation of security updates

AP Exam Prep

Voice assistants, such as Siri, Alexa, and Cortana, are software agents that can recognize and respond to
voice commands. Although these agents wait to hear a "wake word" that activates them to listen and respond
to a voice command, there is still a possibility that the voice data of the user can be exposed.

When developing a voice assistant, what security considerations would a programmer need to address? How
can they make sure that the device is safe for their users?

1
Extra Practice

Do This: In October 2021, New World players discovered that they were able to insert code and manipulate
game functionality by entering it in the chat window. Players can change what others see, block their vision, or
crash their instance of the game. Read the article on the following page, then respond to the following prompts:

What happened? How did they do it?

Who was impacted by this event and how?

What is the ethical obligation of the software engineers addressing this software security issue?

2
Players are gleefully breaking New World with gold duping, chat exploits
By Cass Marshall | Nov 2, 2021

At first glance, New World appears to be a standard MMO experience, with crafting, combat, and monstrous critters to
slay. But there’s a hidden underbelly to the game that players are using to get all manner of unscrupulous advantages.
While New World has lots of in-game PvP opportunities for players to contest regions or duke it out with each other, it’s
also proving to have lots of in-game opportunities to blindside opponents or gain advantages by exploiting the game’s
many, many bugs. And some of developer Amazon’s fixes and patches have also resulted in additional player issues.

New World had bugs from the beginning; all MMOs do. At first, the game’s biggest problem was queues of players trying
to get into the game. Then, people noticed that they could make their character invulnerable by minimizing the game’s
screen and dragging it around. Amazon stepped in to fix that for Patch 1.0.4, but new problems had already emerged.
These issues varied wildly between servers. Some communities had to resort to the barter economy to hoard as much
wealth as possible during a deflation process, while other groups found the key to infinite wealth via duping.

Even mundane features like the chat box became untrustworthy. Fans on the New World subreddit reported that other
players could post HTML code in the chat to blind them, or even disconnect other people from the game. “You can insert
HTML code in the chat to display images or even kick people if they hover over a word,” wrote user janikFIGHT. It’s
certainly an unscrupulous advantage to use the chat box to send a giant yellow square that covers most of your screen.
And even less rude uses of the exploit — like sending a giant stock image of sausages — are still immersion breaking.

This has put Amazon into a position where it needs to fix these bugs, but new patches have the potential to just add new
problems. On Oct. 29, Amazon fixed the image posting bug, which aimed to make chat more secure and avoid this kind of
disruption. On Monday, the developer posted this message on the MMO’s official forums, which reads:

“We are aware of a possible gold duplication exploit that has been circling and we are temporarily disabling all
forms of wealth transfer between players (ie. sending currency, guild treasury, trading post, player to player
trading). Any player that has engaged in the use of this exploit will be actioned against. Once the gold duplication
exploit has been investigated and we are ready to turn on wealth transfer again, we will update this post. Thank
you for your understanding.”

But now, it appears as though this fix opened the way for another gold duplication bug, with players flocking to the official
forums to report the issue. A major part of New World is upgrading your settlement and acting as governor; however,
players are reporting that they can start upgrades, see the gold accumulate in their company bank, and then … the
upgrade simply doesn’t start, which allows them to collect free gold.

This is in addition to a myriad of other, less game-breaking bugs like a hatchet exploit that allows players to solo
end-game areas with ease. While some players are having a blast killing boars and fishing, others are playing a wholly
different game, where they try and see what elements of New World they can bend or break to their advantage. From
there, all the developer can do is scramble to try to catch up.

In a forum thread, a developer under the handle Kay wrote: “I’m being sincere when I say [the glitch is] not funny. We
worked really hard to get those changes that addressed the exploits from Closed Beta, and for another issue to show up
that looks exactly the same, negates our work completely. We created this game for you all, and issues like this one,
where it looks like we are ignoring something that we all consider a huge problem, make it seem like we don’t care. We
care a lot. And I’m sorry that this is happening.”

Source: Marshall, Cass. “New World Is Struggling with Multiple Bugs, Exploits, and Gold Duping.” Polygon, 2 Nov. 2021,
www.polygon.com/22760062/new-world-post-launch-bugs-exploits-chat-gold-duping.

3
CSA Unit 8 Guide

Lesson 9: Privacy and Security


Data Collection
What data is being collected by the apps and programs you use at home? What about at school or related to
your hobbies?

Reflection
Question of the Day: What are the tradeoffs between the utility of data collection and safeguarding privacy
and security?

How could you address data privacy and security concerns when developing your creative coding project?

1
Searching and Sorting
Creative Coding with the Console Project
Resources
Name(s) __________________________________________________ Period _______ Date _____________________

Creative Coding with the Console Project Planning Guide

For this project, you will create a program using the console that portrays a personal interest or solves a
problem that you choose. Your program should demonstrate the object-oriented programming and software
engineering skills and knowledge you have developed throughout the year.

Project Requirements
Use your knowledge of object-oriented programming, data structures, method decomposition, and algorithms
to create your program:

● Use inheritance and polymorphism – Create a superclass that represents shared attributes and
behaviors with at least two subclasses that are more specific versions or variations of the superclass.

● Method decomposition – Use overloaded, overridden, and private methods to implement different
versions of the same behavior, variations of a superclass behavior, and to improve code organization.

● Use at least two data structures – Use at least two 1D or 2D arrays or ArrayLists to store elements
that are manipulated using loops and conditionals.

● Implement one or more algorithms – Implement one or more algorithms that use loops and two-way
or multi-selection statements with compound Boolean expressions to analyze the data.

● Document your code – Use comments to explain the purpose of the methods and code segments and
note any preconditions and postconditions.

Optional Features
● Incorporate user interaction – Use methods in the Scanner class to obtain user input to interact with
your creative coding program.

● Use static variables, constants, and/or static methods – Use static variables to represent values
that are shared by all objects of a class, a constant to represent a value that doesn't change, and/or a
static method to represent a behavior that doesn't require an object or as a helper method.

● Use methods in the String class – Use one or more methods in the String class in your program,
such as to determine if a String contains specific characters or obtain a substring from a String.

● Use methods in the Math class – Use one or more methods in the Math class in your program, such
as to perform calculations on the values in a 2D array and display the results, choose random values
from the 2D array.

1
Project Benchmarks
Benchmark #1 Due Lesson 6
Brainstorm project ideas and goals

Decompose the problem to identify the classes and methods you will need
to implement

Obtain and implement feedback from peers

Benchmark #2 Due Lesson 8


Develop one or more classes and data structures

Implement one or more algorithms to create a visual or animation

Obtain and implement feedback from peers

Benchmark #3 Due End of Project


Self-assess your work using the program requirements and rubric

Finalize your program using the feedback you received and your
self-assessment

Showcase your work!

2
Project Rubric
Category Extensive Evidence Convincing Evidence Limited Evidence No Evidence

Inheritance and Creates a superclass and at Creates a superclass and one Creaets a superclass and a Does not create a superclass
Polymorphism least two subclasses that subclass that demonstrate subclass but does not use and subclass relationship.
demonstrate effective use of basic use of inheritance and these principles in meaningful
inheritance and polymorphism. or effective ways.
polymorphism.

Method Decomposition Writes multiple overloaded, Writes some overloaded, Writes some overloaded, Does not write any
overridden, and private overridden, and/or private overridden, and/or private overloaded, overridden, or
methods that effectively methods that implement methods, but their private methods.
implement different versions different versions of the same implementation is not
of the same behavior and behavior or variations of a effective or they do not
variations of a superclass superclass behavior, but the improve code organization.
behavior, resulting in code could be better
well-organized code. organized.

Data Structures Uses at least two 1D or 2D Uses at least one 1D or 2D Uses at least one 1D or 2D Does not use any 1D or 2D
arrays or ArrayLists that are array or ArrayList that is array or ArrayList, but it is arrays or ArrayLists.
effectively manipulated using effectively manipulated using not manipulated using loops
loops and conditionals. loops and conditionals. and conditionals.

Algorithms Implements more than one Implements one algorithm Implements one algorithm Does not implement an
algorithm using the data using a data structure. using a data structure but algorithm using a data
structures. does not loops and use structure.
AND two-way or multi-selection
AND statements with compound
The algorithm uses loops and Boolean expressions to
More than one algorithm uses two-way or multi-selection analyze the data and create
loops and two-way or statements with compound the visualization.
multi-selection statements Boolean expressions to
with compound Boolean analyze the data and create
expressions to analyze the the visualization.
data and create the
visualization.

3
Category Extensive Evidence Convincing Evidence Limited Evidence No Evidence

Documentation Uses single and multi-line Uses single-line comments to Uses single-line comments to Does not use comments to
comments to explain the explain the functionality and explain the functionality and document the functionality
functionality and purpose of purpose of methods and code purpose of methods in the and purpose of methods or
methods and code segments segments in the program program code segments in the
in the program program

4
Step 1: Breaking Down the Project
Identify Need to Knows
Consider what you already know and need to know to complete this project. Use these questions to guide and track your progress throughout the
unit and the project. Don't forget to add new questions to your Need to Know list as you learn more!

Know Need to Know Learned

5
Common Characteristics and Features
Review and analyze each of the project examples on Code Studio. As you review, use the box below to
generate a list of some common characteristics and key features that you see. This is simply an
investigation to see what you notice. We will cover some of the main project requirements throughout the
lessons of this unit.

6
Step 2: Brainstorming
For your project, you will choose a topic or problem you want to portray or address using the console.
Brainstorm ideas for things you are interested in or problems you want to address and ways that you want to
convey your topic with the console. For example:

● Option #1: Your business from the Store Management Project has expanded to multiple locations, and
you want to learn more about what makes each location uniquely successful! Create a program that
analyzes data across all your locations.

● Option #2: Expand your Data for Social Good Project to do more complex analysis. Model the data
using classes instead of primitive values.

● Option #3: Expand your Natural Language Processing Project to do more complex analysis. For
example, you want to find the most common word or the longest sentence in the text. Model the data
using classes instead of Strings.

● Option #4: Create a text based game.

● Option #5: Develop a program to keep track of items. For example, keep track of family recipes or
manage a To-Do list.

What personal interest do you want to portray or what problem do you want to address with your
program?

How do you want to convey your topic in a program using the console?

7
Step 3: User Stories
A user story is a short explanation of a program feature that is written from the end user's point of view to
describe how the feature will provide value to the user. User stories are often expressed in short sentences,
like "As a [persona], I [want to], [so that]." You should write a user story for each large step or component of
your overall project. For each user story:

● Identify the criteria for what it means for it to be considered "done".

● Decide which specific steps need to be completed for it to be considered "done".

User Story Criteria Steps to Complete

8
Step 4: Planning and Design
UML Diagrams

Create a UML diagram for your


class that will represent the scene
and any additional classes you
might need.

9
Step 5: Decompose the Problem
Class:

Method

Precondition(s)

Postcondition(s)

Pseudocode

10
Class:

Method

Precondition(s)

Postcondition(s)

Pseudocode

11
Step 6: Acceptance Testing
Test the acceptance criteria for your user stories. Your reviewer should test your program and determine which
of your user stories are complete and which ones still need work.

Criteria Passed Notes

12
Day 2: Software Engineers
How are you being a problem-solver while you are working on your project?

How are you being creative while you are working on your project?

13
End of Project Reflection
Describe your project.

What are two things about your project that you are proud of?

Describe something you would improve or do differently if you had an opportunity to change something about
your project.

14
Searching and Sorting
SeatingChart FRQ
Resources
Java Quick Reference
Accessible methods from the Java library that may be included in the exam
Class Constructors and Methods Explanation
String Class
String(String str) Constructs a new String object that represents the same sequence of
characters as str

int length() Returns the number of characters in a String object


String substring(int from, Returns the substring beginning at index from and ending at index to - 1
int to)
String substring(int from) Returns substring(from, length())
int indexOf(String str) Returns the index of the first occurrence of str; returns -1 if not found
boolean equals(String other) Returns true if this is equal to other; returns false otherwise
int compareTo(String other) Returns a value <0 if this is less than other; returns zero if this is
equal to other; returns a value >0 if this is greater than other
Integer Class
Integer(int value) Constructs a new Integer object that represents the specified int value
Integer.MIN_VALUE The minimum value represented by an int or Integer
Integer.MAX_VALUE The maximum value represented by an int or Integer
int intValue() Returns the value of this Integer as an int
Double Class
Double(double value) Constructs a new Double object that represents the specified double value
double doubleValue() Returns the value of this Double as a double
Math Class
int abs(int x) Returns the absolute value of an int value
double abs(double x) Returns the absolute value of a double value
double pow(double base, Returns the value of the first parameter raised to the power of the second
double exponent) parameter

double sqrt(double x) Returns the positive square root of a double value


double random() Returns a double value greater than or equal to 0.0 and less than 1.0
ArrayList Class
int size() Returns the number of elements in the list

boolean add(E obj) Appends obj to end of list; returns true


void add(int index, E obj) Inserts obj at position index (0 <= index <= size), moving
elements at position index and higher to the right (adds 1 to their indices) and
adds 1 to size

E get(int index) Returns the element at position index in the list


E set(int index, E obj) Replaces the element at position index with obj; returns the element
formerly at position index

E remove(int index) Removes element from position index, moving elements at position
index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1
from size; returns the element formerly at position index
Object Class
boolean equals(Object other)
String toString()

© 2019 College Board


Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - SeatingChart FRQ

Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN
IN JAVA. You may plan your answers on a scratch piece of paper, but no credit will be given for anything
written on a scratch piece of paper. You will only earn credit for what you write on the response pages.

Notes:

● Assume that the classes listed in the Java Quick Reference have been imported where appropriate.

● Unless otherwise noted in the question, assume that parameters in method calls are not null and that
methods are called only when their preconditions are satisfied.

● In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

1
A seating chart contains rows of students with the same number of students in each row.

The Student class, shown below, represents students in the seating chart. The instance variable attendance
is assigned "P" if the student was present (in class and on time), "T" if the student was tardy (in class but
late), and "A" if the student was absent (not in class). The instance variable group represents the group
number that the student is in.

public class Student


{
private String attendance;
private int group;

public Student(String a, int g)


{
attendance = a;
group = g;
}

public String getAttendance()


{ return attendance; }

public int getGroup()


{ return group; }

2
The SeatingChart class represents the seating chart for a single day.

public class SeatingChart


{
private Student[][] seatingChart;

// Constructor not shown

/** Returns the proportion of students in a group that are not absent
* as described in part (a).
* Precondition: there is at least one Student in group g, and there is a Student at each
* element of seatingChart.
*/
public double propNotAbsent(int g)
{ /* to be implement in part (a) */ }

/** Returns the first row that has all students present, or -1 if there are no
* rows with all students present.
* Precondition: there is at least one Student in the seatingChart, and there is a Student
* at each element of seatingChart.
*/
public int rowPresent()
{ /* to be implement in part (b) */ }
}

3
a. Write the method propNotAbsent that returns the proportion of students in the group specified by the
parameter g that are not absent. For example, if seatingChart contains the following seating chart:

0 1 2 3

0
"A" "P" "T" "T"
1 2 3 1

1
"P" "P" "P" "P"
1 2 3 1

2
"P" "P" "P" "P"
1 2 3 3

The call to propNotAbsent with the parameter 1 would return 0.8 because there are five Student objects
in group 1, and four of them are not "A" for absent (one Student in group 1 is "T" for tardy, and three
Student objects in group 1 are "P" for present).

WRITE YOUR SOLUTION ON THE PROVIDED RESPONSE PAGE.

4
b. Write the method rowPresent that returns the first row that has all students present, or -1 if there are no
rows with all students present. For example, if seatingChart contains the following seating chart:

0 1 2 3

0
"A" "P" "T" "T"
1 2 3 1

1
"P" "P" "P" "P"
1 2 3 1

2
"P" "P" "P" "P"
1 2 3 3

The call to rowPresent would return 1 since row 1 is the first row that has all students marked "P" for
present. Even though row 2 also has all students "P" for present, 1 is returned because that is the first row
with all students "P" for present.

WRITE YOUR SOLUTION ON THE PROVIDED RESPONSE PAGE.

5
FRQ Response
Important: Completely fill in the circle that corresponds to the question that Part (a) Part (b)
you are answering on this page.

Begin your response to each question at the top of a new page.

Use a pencil only. Do NOT write outside the box.


6
FRQ Response
Important: Completely fill in the circle that corresponds to the question that Part (a) Part (b)
you are answering on this page.

Begin your response to each question at the top of a new page.

Use a pencil only. Do NOT write outside the box.


7
Name(s) __________________________________________________ Period _______ Date _____________________

Activity Guide - SeatingChart FRQ Scoring Guidelines

Part (a) propNotAbsent() 5 points

+1 Counts the number of non-absent students

+1 Counts the total number of students in the group

+1 Accesses all entries in seatingChart (no bounds errors)

+1 Uses getGroup to obtain the Student object's group

+1 Returns the correct double proportion of students

Part (b) rowPresent() 4 points

+1 Accesses all necessary elements in at least one row of seatingChart (no bounds errors)

+1 Uses getAttendance to obtain a Student object's attendance

+1 Checks if all Student objects in a row are not absent

+1 Returns the first row that has all students not absent, or -1 if there are none

You might also like