Searching and Sorting Resources
Searching and Sorting Resources
Project Planning
Resources
Name(s) __________________________________________________ Period _______ Date _____________________
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
Finalize your program using the feedback you received and your
self-assessment
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!
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 #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:
8
Step 4: Planning and Design
UML Diagrams
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.
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 _____________________
1
AP Exam Prep
The following code segment is intended to return the location of a target element in an ArrayList.
Which of the following conditions will cause the given code segment to not work as intended?
D. The size of the ArrayList is less than the expected number of elements.
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.
3
CSA Unit 8 Guide
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 _____________________
/* 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.
"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.
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.
containsName(seatingChart, _______);
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 _____________________
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)?
A. I only
B. II only
C. III only
D. I and II 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:
return -1;
}
Which of the following best explains why the method does not work as intended?
C. When target is not the last element, it returns -1 instead of traversing the rest of the array.
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 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
1
CSA Unit 8 Guide
average case
2
CSA Unit 8 Guide
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 ______________________________
1
Test Your Algorithm
Use the cards to test your algorithm. Modify your algorithm until it correctly locates the card.
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.
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.
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.
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 _____________________
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?
A. 4
B. 5
C. 9
D. 10
E. 11
1
AP Exam Prep
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.
3
CSA Unit 8 Guide
Binary Search
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
public static int binarySearch(int[] arr, int low, int high, int target) {
return -1;
if (arr[mid] == target) {
return mid;
else {
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 _____________________
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 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 _____________________
Consider the following sort method. This method correctly sorts the elements of array data into increasing
order.
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 */) ?
1
AP Exam Prep
The following declaration and method call appears in the same class as selectSort.
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
3
CSA Unit 8 Guide
Selection Sort
selection sort
1
CSA Unit 8 Guide
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 _____________________
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 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 _____________________
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:
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 _____________________
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.
AP Exam Prep
Complete the code segment below by adding the missing code to correctly implement insertion sort.
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}
{2, 5, 9, 10}
{4, 7, 72, 9, 1, 9, 7}
2
CSA Unit 8 Guide
insertion sort
while next is greater than or equal to 0 and the value at next is greater than current
decrement next
What qualities are important when deciding whether one algorithm is better than another?
1
CSA Unit 8 Guide
2
CSA Unit 8 Guide
Reflection
Question of the Day: How does the insertion sort algorithm compare in efficiency with the selection sort
algorithm?
3
Searching and Sorting
Merge Sort
Resources
Name(s) __________________________________________________ Period _______ Date _____________________
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].
1
Name(s) __________________________________________________ Period _______ Date _____________________
Consider the following code segment, which appears in a method in the same class as mergeSortHelper and
merge.
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.
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
1
CSA Unit 8 Guide
Merge Sort
merge sort
helper method
2
CSA Unit 8 Guide
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 _____________________
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?
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:
3
CSA Unit 8 Guide
Searching Algorithms
How does the linear search algorithm work?
1
CSA Unit 8 Guide
Sorting Algorithms
How does the selection sort algorithm work?
2
CSA Unit 8 Guide
Reflection
Question of the Day: How can I implement searching and sorting algorithms when working multiple lists?
3
Searching and Sorting
Project Development
Resources
Name(s) __________________________________________________ Period _______ Date _____________________
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.
1
AP Exam Prep
Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of
integers.
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 }
Consider the following code segment, which appears in a method in the same class as mergeSortHelper and
merge.
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
3
Searching and Sorting
Privacy and Security
Resources
CSA Unit 8 Study Guide
Objectives
In this unit, you learned:
● Analyze the efficiency of searching and sorting algorithms using execution counts
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
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
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
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
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
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
7
Syntax
public void merge(int[] leftList, int[] rightList, int[] myList, int left, int right) {
int index = 0;
int leftIndex=0;
int rightIndex = 0;
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 _____________________
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
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
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 _____________________
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
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 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
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 _____________________
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
Finalize your program using the feedback you received and your
self-assessment
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!
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 #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:
8
Step 4: Planning and Design
UML Diagrams
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.
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
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()
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.
2
The SeatingChart class represents the seating chart for a single day.
/** 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).
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.
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.
+1 Accesses all necessary elements in at least one row of seatingChart (no bounds errors)
+1 Returns the first row that has all students not absent, or -1 if there are none