CompSci A Course Description
CompSci A Course Description
CompSci A Course Description
SCIENCE A
Course Description
E F F E C T I V E FA L L 2 014
AP Course Descriptions
AP Course Descriptions are updated regularly. Please visit AP Central (apcentral.collegeboard.org) to determine
whether a more recent Course Description PDF is available.
2014 The College Board. College Board, ACCUPLACER, Advanced Placement Program, AP, AP Central, SAT, SpringBoard, and the acorn
logo are registered trademarks of the College Board. PSAT/NMSQT is a registered trademark of the College Board and National Merit
Scholarship Corporation. All other products and services may be trademarks of their respective owners. (Visit the College Board on the
Web: www.collegeboard.org.)
Contents
About the AP Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Offering AP Courses and Enrolling Students. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How AP Courses and Exams Are Developed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How AP Exams Are Scored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Additional Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
1
2
2
3
AP Computer Science A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Important Revisions to This Course Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
The Course. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Goals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Computer Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Teaching the Course. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Topic Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Commentary on the Topic Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Java Library Classes and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Lab Requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The Exam. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Computer Science A: Sample Multiple-Choice Questions. . . . . . . . . . . . . . . . . . . 18
Answers to Computer Science A Multiple-Choice Questions . . . . . . . . . . . . 43
Sample Free-Response Questions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Suggested Solutions to Free-Response Questions. . . . . . . . . . . . . . . . . . . . . 57
Appendix A: AP Computer Science Java Subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Appendix B: Exam Appendix Java Quick Reference . . . . . . . . . . . . . . . . . . . . . . . 67
Appendix C: Sample Search and Sort Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Sequential Search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Binary Search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Resources for AP Teachers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
AP Central (apcentral.collegeboard.org) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
AP Course Audit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Advances in AP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
AP Teacher Communities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Higher Ed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
College Board Store. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
77
77
77
77
77
77
77
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
College faculty are involved in every aspect of AP, from course and exam development
to scoring and standards alignment. These faculty members ensure that the courses and
exams meet colleges expectations for content taught in comparable college courses.
Based upon outcomes research and program evaluation, the American Council on
Education (ACE) and the Advanced Placement Program recommend that colleges grant
credit and/or placement to students with AP Exam scores of 3 and higher. The AP score
of 3 is equivalent to grades of B-, C+, and C in the equivalent college course. However,
colleges and universities set their own AP credit, advanced standing, and course
placement policies based on their unique needs and objectives.
Score
5
4
3
2
1
Recommendation
Extremely well qualified
Well qualified
Qualified
Possibly qualified
No recommendation
Additional Resources
Visit apcentral.collegeboard.org for more information about the AP Program.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
INTRODUCTION
Computer science embraces problem solving, hardware, algorithms, and perspectives
that help people utilize computers to address real-world problems in contemporary life.
As the study of computer science is evolving, the careful design of the AP Computer
Science A course and exam continues to strive to engage a diverse student population,
including female and underrepresented students, with the rigorous and rewarding
concepts of computer science. Students who take the AP Computer Science A course
and exam are well prepared to continue their study of computer science and its
integration into a wide array of computing and STEM-related fields.
The AP Computer Science A curriculum provides resources, such as applicationrelated labs, that connect with students with diverse interests, particularly female and
underrepresented student populations. The course is engaging and underscores the
importance of communicating solutions appropriately and in ways that are relevant to
current societal needs. Thus, a well-designed, modern AP Computer Science A course
can help address traditional issues of equity, access, and broadening participation in
computing while providing a strong and engaging introduction to fundamental areas
of the discipline.
The AP Computer Science A course introduces students to computer science with
fundamental topics that include problem solving, design strategies and methodologies,
organization of data (data structures), approaches to processing data (algorithms),
analysis of potential solutions, and the ethical and social implications of computing.
The course emphasizes both object-oriented and imperative problem solving and
design. These techniques represent proven approaches for developing solutions that
can scale up from small, simple problems to large, complex problems. For a listing of
the topics addressed, see the Computer Science A topic outline on pages 810.
The AP Computer Science A course curriculum is compatible with many CS1
courses in colleges and universities. Some colleges and universities may organize their
curricula in alternative ways, so that the topics of the AP Computer Science A course
are spread over several college courses, with other topics from computer science
interspersed.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
THE COURSE
The AP Computer Science A course is an introductory course in computer science.
The major theme of the course is problem solving. The topic outline on pages 810
summarizes the content required in the AP Computer Science A course.
Goals
The goals of the AP Computer Science A course are comparable to those in the
introductory course for computer science majors offered in many college and university
computer science departments. It is not expected that all students in the AP Computer
Science A course will major in computer science at the university level. The AP
Computer Science A course is intended to serve both as an introductory course for
computer science majors and as a course for people who will major in other disciplines
and want to be informed citizens in todays technological society.
The following goals apply to the AP Computer Science A course. Students should be
able to:
design, implement, and analyze solutions to problems.
use and implement commonly used algorithms.
use standard data structures.
develop and select appropriate algorithms and data structures to solve new
problems.
write solutions fluently in an object-oriented paradigm.
write, run, test, and debug solutions in the Java programming language, utilizing
standard Java library classes and interfaces from the AP Java subset.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Computer Language
Because the discipline of computer science emphasizes problem solving, study of the
discipline requires a mechanism to express potential solutions precisely and concisely.
Since any natural language (e.g., English) allows inconsistencies and ambiguities,
solutions in computer science require a communication medium more formal than a
natural language. For this reason, the AP Computer Science A course requires that
potential solutions of problems be written in the Java programming language. In
addition to precision of expression, Java supports important elements of problem
solving, including object-orientation, abstraction, and encapsulation. The use of Java
also allows students to test potential solutions to problems by running programs.
Because the Java programming language is extensive with far more features than
could be covered in a single introductory course, the AP Computer Science A Exam
covers a subset of Java. The AP Java subset can be found in Appendix A.
Resources
Students should have access to a computer system that represents relatively recent
technology. A school should ensure that each student has access to a computer for at
least three hours a week; additional time is desirable. Student and instructor access to
computers is important during class time, but additional time is essential for students
to develop solutions to problems individually.
The computer system must allow students to create, edit, compile quickly, and
execute Java programs comparable in size to those found in the AP Computer Science
Labs. It is highly desirable that these computers provide student access to the Internet.
It is essential that each computer science teacher has Internet access.
A school must ensure that each student has a college-level text for individual use
inside and outside of the classroom. Schools are encouraged to provide copies of the
lab materials for individual use.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Prerequisites
The assumed prerequisites for entering the AP Computer Science A course include
knowledge of basic English and algebra. A student in the AP Computer Science A
course should be comfortable with functions and the concepts found in the uses of
function notation, such as f(x) = x + 2 and f(x) = g(h(x)). It is important that students
and their advisers understand that any significant computer science course builds
upon a foundation of mathematical reasoning that should be acquired before
attempting such a course.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
TOPIC OUTLINE
Following is an outline of the major topics considered for the AP Computer Science A
Exam. This outline is intended to define the scope of the course, but not the sequence.
I. Object-Oriented Program Design
The overall goal for designing a piece of software (a computer program) is to correctly
solve the given problem. At the same time, this goal should encompass specifying and
designing a program that is understandable, and can be adapted to changing
circumstances. The design process needs to be based on a thorough understanding of
the problem to be solved
A. Program and Class Design
1. Problem analysis
2.
Data abstraction and encapsulation
3.
Class specifications, interface specifications, relationships (is-a, has-a), and
extension using inheritance
4.
Code reuse
5.
Data representation and algorithms
6.
Functional decomposition
II. Program Implementation
Part of the problem-solving process is the statement of solutions in a precise form that
invites review and analysis. The implementation of solutions in the Java programming
language reinforces concepts, allows potential solutions to be tested, and encourages
discussion of solutions and alternatives.
A. Implementation techniques
1. Top-down
2. Bottom-up
3. Object-oriented
4. Encapsulation and information hiding
5. Procedural abstraction
B. Programming constructs
1. Primitive types vs. reference types
2. Declaration
a.
Constants
b.
Variables
c. Methods and parameters
d.
Classes
e.
Interfaces
3. Text output using System.out.print and System.out.println
4. Control
a.
Method call
b.
Sequential execution
c.
Conditional execution
d.
Iteration
e.
Recursion
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
5. Expression evaluation
a.
Numeric expressions
b.
String expressions
c. Boolean expressions, short-circuit evaluation, De Morgans law
C. Java library classes and interfaces included in the AP Java Subset
III. Program Analysis
The analysis of programs includes examining and testing programs to determine
whether they correctly meet their specifications. It also includes the analysis of
programs or algorithms in order to understand their time and space requirements
when applied to different data sets.
A. Testing
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
10
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
12
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
J AVA L I B R A R Y C L A S S E S A N D I N T E R FA C E S
An important aspect of modern programming is the existence of extensive libraries
that supply many common classes and methods. An essential programming skill is the
ability to appropriately use available libraries. The AP Computer Science A curriculum
specifies a subset of classes and interfaces from the Java libraries with which students
should be familiar.
In addition, students should recognize possibilities for reusing components of their
own code or of other examples of code, such as the AP Computer Science Labs, in
different programs.
13
Students are responsible for understanding the Java String class and the methods
of the String class that are listed in the Java Quick Reference (see Appendix B).
Students should be comfortable working with 1-dimensional and 2-dimensional
arrays. They need to understand that 2-dimensional arrays are stored as arrays of
arrays. For the purposes of the AP Computer Science A Exam, students should
assume that 2-dimensional arrays are rectangular (not ragged) and the elements are
indexed in row-major order.
Students should be able to use lists of data and be able to use Java arrays and the
ArrayList class to implement such lists. They should be able to use either of these
list types in a program and should be able to select the most appropriate one for a
given application. The methods for the List interface (and its implementation by the
ArrayList class) for which students are responsible are specified in the Java Quick
Reference (see Appendix B).
14
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
LAB REQUIREMENTS
Although the AP Computer Science A course draws heavily upon theory, formal logic,
abstract data structures, and a conceptual understanding of algorithms, students also
must gain significant experience applying the concepts to tackle a wide range of
problems. As students design data structures and develop algorithms, the students
should integrate ideas, test hypotheses, and explore alternative approaches. Further,
activities motivated by real-world applications can provide insights about how
computing can be useful in society, motivate the study of technical issues, and capture
students interest.
The AP Computer Science A course must include a minimum of 20 hours of
hands-on structured-lab experiences to engage students in individual or group
problem solving. Thus, each AP Computer Science A course must include a substantial
laboratory component in which students design solutions to problems, express their
solutions precisely (i.e., in the Java programming language), test their solutions,
identify and correct errors (when mistakes occur), and compare possible solutions.
Collectively, these laboratory experiences and activities should contain the following
characteristics:
Explore computing in context at a significant level, building upon existing code
that provides examples of good style and appropriate use of programming
language constructs.
Contain a significant problem-solving component in which students study
alternative approaches for solving a problem, solve new problems, or modify
existing code to solve altered problems.
Provide students with experience working with programs involving multiple
interactive classes and may involve decomposing a program into classes and
using inheritance, interfaces, and other object-oriented concepts as identified in
the AP Computer Science A topic outline.
Three exemplar labs, the AP Computer Science A Labs, have been developed for teachers
to use in the AP Computer Science A course. AP Computer Science A teachers will be
able to access all instructional resources for each lab (Teacher and Student Guides,
solutions and code files) through their AP Course Audit accounts. The first lab (Magpie)
can be incorporated early in the course and involves simple string processing and
conditional execution. The second lab (Picture Lab) involves 2-dimensional array
manipulation in the context of image processing. The third lab (Elevens) provides an
example of larger object-oriented program design. The AP Computer Science Labs include
teacher and student guides along with Java code. Each teacher guide includes concepts
covered, learning objectives, necessary prerequisite knowledge, guidelines on when each
lab might fit naturally into a course, suggestions on the use of the materials, suggested
problems and questions for use during each activity, and sample assessment exercises.
The Student Guides for the AP Computer Science A Labs can be found on the AP
Computer Science home page:
http://apcentral.collegeboard.com/apc/public/courses/teachers_corner/222163.html
Teachers may use the provided labs, develop their own labs and/or utilize laboratory
exercises from textbook authors or other sources. When choosing labs, teachers must
carefully evaluate the activities, objectives, and materials to be certain that the labs
address the characteristics outlined above.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
15
Resource Requirements
The school ensures that each student has a college-level text for individual use
inside and outside of the classroom and has access to the AP Computer Science
A Labs.
The school ensures that each student has access to a computer for at least three
hours a week; three hours are the bare minimum, additional time is desirable.
The computer system must contain appropriate software to create and edit
programs and must allow programs comparable in size to the current AP
Computer Science A Labs to compile in seconds. Internet access is strongly
encouraged.
16
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
THE EXAM
The AP Computer Science A Exam is 3 hours long and seeks to determine how well
students have mastered the concepts and techniques contained in the course outline.
The exam consists of two sections: a multiple-choice section (40 questions in 1 hour
and 30 minutes), which tests proficiency in a wide variety of topics, and a freeresponse section (4 questions in 1 hour and 30 minutes), which requires the student to
demonstrate the ability to solve problems involving more extended reasoning.
The multiple-choice and the free-response sections of the AP Computer Science A
Exam require students to demonstrate their ability to solve problems, including their
ability to design, write, and analyze programs and subprograms. Minor points of
syntax are not tested on the exam. All code given is consistent with the AP Java subset.
All student responses involving code must be written in Java. Students are expected to
be familiar with and able to use the standard Java classes and interfaces listed in the
AP Java subset. For both the multiple-choice and the free-response sections of the
exam, a quick reference to the classes and interfaces in the AP Java subset will be
provided. The Java Quick Reference is included in Appendix B.
In the determination of the grade for the exam, the multiple-choice section and the
free-response section are given equal weight. Because the exam is designed for full
coverage of the subject matter, it is not expected that many students will be able to
correctly answer all the questions in either the multiple-choice section or the freeresponse section in the time allotted.
Multiple-choice questions on the exam are classified according to the type of
content that is tested in the question. Questions may be listed in one or more of the
classification categories. For example, a question that uses a looping construct to
traverse the elements of an array would be listed under both the Data Structures and
the Programming Fundamentals categories. The table below shows the classification
categories and how they are represented in the multiple-choice section of the exam.
Because questions can be classified in more than one category, the total of the
percentages is greater than 100%.
Classification Categor y
Percent of
multiple-choice items
Programming Fundamentals
5575%
Data Structures
2040%
Logic
515%
Algorithms/Problem Solving
2545%
Object-Oriented Programming
1525%
Recursion
515%
Software Engineering
210%
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
17
Following is a representative set of questions. The answer key for the Computer
Science A multiple-choice questions is on page 43. Multiple-choice scores are based on
the number of questions answered correctly. Points are not deducted for incorrect
answers, and no points are awarded for unanswered questions. Because points are not
deducted for incorrect answers, students are encouraged to answer all multiple-choice
questions. Students should eliminate as many choices as they can on any questions for
which they do not know the answer, and then select the best answer among the
remaining choices.
Directions: Determine the answer to each of the following questions or incomplete
statements, using the available space for any necessary scratch work. Then decide
which is the best of the choices given and fill in the corresponding circle on the
answer sheet. No credit will be given for anything written in the examination booklet.
Do not spend too much time on any one problem
Notes:
Assume that the classes listed in the Java Quick Reference have been imported
where appropriate.
Assume that declarations of variables and methods appear within the context of
an enclosing class.
Assume that method calls that are not prefixed with an object or class name and
are not shown within a complete class definition appear within the context of an
enclosing class.
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.
18
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
16
(b) 4
10
(c) 0
12
(d) 1
10
(e) 0
16
18
13
8
16
10
19
12
14
16
18
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
19
[0, 0, 4, 2, 5, 0, 3, 0]
20
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
4. At a certain high school students receive letter grades based on the following
scale.
Integer Score
93 or above
From 84 to 92 inclusive
Letter Grade
A
B
From 75 to 83 inclusive
Below 75
Which of the following code segments will assign the correct string to grade
for a given integer score ?
(a) II only
(b) III only
(c) I and II only
(d) I and III only
(e) I, II, and III
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
21
1
2
3
4
1
2
3
1
2
6. A car dealership needs a program to store information about the cars for sale. For
each car, they want to keep track of the following information: number of doors
(2 or 4), whether the car has air conditioning, and its average number of miles
per gallon. Which of the following is the best object-oriented program design?
(a) Use one class, Car, with three instance variables:
int numDoors, boolean hasAir, and
double milesPerGallon.
(b) Use four unrelated classes: Car, Doors, AirConditioning, and
MilesPerGallon.
(c) Use a class Car with three subclasses: Doors, AirConditioning, and
MilesPerGallon.
(d) Use a class Car, with a subclass Doors, with a subclass
AirConditioning, with a subclass MilesPerGallon.
(e) Use three classes: Doors, AirConditioning, and MilesPerGallon,
each with a subclass Car.
7. Consider the following declarations.
public interface Shape
{
int isLargerThan(Shape other);
// Other methods not shown
}
public class Circle implements Shape
{
// Other methods not shown
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
23
24
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
8. Which of the following can be used to replace /* missing code */ so that advance
will correctly update the time?
timeCards[k].minutes)
(d) total.advance(timeCards[k].getHours(),
timeCards[k].getMinutes())
(e) timeCards[k].advance(timeCards[k].getHours(),
timeCards[k].getMinutes())
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
25
*
*
@param low an int value such that 0 < low < arr.length
@param high an int value such that low - 1 < high < arr.length
*/
public int mystery(int low, int high, int num)
{
int mid = (low + high) / 2;
if (low > high)
{
return low;
}
else if (arr[mid] < num)
{
return mystery(mid + 1, high, num);
}
else if (arr[mid] > num)
{
return mystery(low, mid 1, num);
}
else // arr[mid] == num
{
return mid;
}
}
26
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
27
11. The method findLongest does not work as intended. Which of the following
best describes the value returned by a call to findLongest ?
(a) It is the length of the shortest consecutive block of the value target
in nums.
(b) It is the length of the array nums.
(c) It is the number of occurrences of the value target in nums.
(d) It is the length of the first consecutive block of the value target in nums.
(e) It is the length of the last consecutive block of the value target in nums.
12. Which of the following changes should be made so that method findLongest
will work as intended?
(a) Insert the statement lenCount = 0;
between lines 2 and 3.
(b) Insert the statement lenCount = 0;
between lines 8 and 9.
(c) Insert the statement lenCount = 0;
between lines 10 and 11.
(d) Insert the statement lenCount = 0;
between lines 11 and 12.
(e) Insert the statement lenCount = 0;
between lines 12 and 13.
28
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Which of the following best describes the contents of numbers after the
following statement has been executed?
int m = mystery(n);
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
29
30
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Assume that the following declaration appears in a class other than Dog.
Dog fido = new UnderDog();
What is printed as a result of the call fido.act() ?
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
31
32
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
(a) Returns the index of the first element in array array whose value is
greater than array[loc]
(b) Returns the index of the last element in array array whose value is greater
than array[loc]
(c) Returns the largest value in array array
(d) Returns the index of the largest value in array array
(e) Returns the index of the largest value in the second half of array array
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
33
When the call test() is executed, what are the values of s and n at the
point indicated by /* End of method */ ?
34
(a) world
(b) worldpeace
(c) world
12
(d) worldpeace
12
(e) peace
12
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
What are the contents of mat after the code segment has been executed?
(a) {{2,
{3,
{3,
{3,
1,
2,
3,
3,
1},
1},
2},
3}}
(b) {{2,
{1,
{1,
{1,
3,
2,
1,
1,
3},
3},
2},
1}}
35
Assume that doSome is called and executes without error. Which of the
following are possible combinations for the value of lim, the number of times
Statement S is executed, and the number of times Statement T is executed?
Value of
lim
Executions of
Statement S
Executions of
Statement T
I.
II.
III.
(a) I only
(b) II only
(c) III only
(d) I and III only
(e) II and III only
36
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
21. Consider the following instance variable, arr, and incomplete method,
partialSum. The method is intended to return an integer array sum such that
for all k, sum[k] is equal to arr[0] + arr[1] + ... + arr[k]. For
instance, if arr contains the values { 1, 4, 1, 3 }, the array sum will
contain the values { 1, 5, 6, 9 }.
Implementation 2
37
22. Consider the following declaration for a class that will be used to represent points
in the xy-coordinate plane.
public class Point
{
private int x;
private int y;
public Point()
{
x = 0;
y = 0;
}
public Point(int a, int b)
{
x = a;
y = b;
}
// Other methods not shown
}
The following incomplete class declaration is intended to extend the above class
so that points can be named.
public class NamedPoint extends Point
{
private String name; // name of point
// Constructors go here
// Other methods not shown
}
38
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
II.
III.
public NamedPoint()
{
name = "";
}
public
{
x =
y =
name
}
(a) I only
(b) II only
(c) III only
(d) I and III only
(e) II and III only
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
39
23. Consider a shuffle method that is intended to return a new array that contains
all the elements from nums, but in a different order. Let n be the number of
elements in nums. The shuffle method should alternate the elements from
nums[0] nums[n / 2 1] with the elements from nums[n / 2]
nums[n 1], as illustrated in the following examples.
Example 1
nums
0
10
1
20
2
30
3
40
4
50
5
60
6
70
7
80
result
0
10
1
50
2
20
3
60
4
30
5
70
6
40
7
80
nums
0
10
1
20
2
30
3
40
4
50
5
60
6
70
result
0
10
1
40
2
20
3
50
4
30
5
60
6
70
Example 2
The following implementation of the shuffle method does not work as intended.
{
int n = nums.length;
int[] result = new int[n];
for (int j = 0; j < n / 2; j++)
{
result[j * 2] = nums[j];
result[j * 2 + 1] = nums[j + n / 2];
}
return result;
}
Which of the following best describes the problem with the given implementation of
the shuffle method?
40
24. Consider the following Util class, which contains two methods. The completed
sum1D method returns the sum of all the elements of the 1-dimensional array a.
The incomplete sum2D method is intended to return the sum of all the elements
of the 2-dimensional array m.
Assume that sum1D works correctly. Which of the following can replace
/* missing code */ so that the sum2D method works correctly?
I. for (int k = 0; k < m.length; k++)
{
sum += sum1D(m[k]);
}
41
25. The following sort method correctly sorts the integers in elements into
ascending order.
Line 1:
Line 2:
Line 3:
Line 4:
Line 5.
int index = j;
Line 6:
Line 7:
Line 8:
Line 9:
Line 10:
Line 11:
index = k;
Line 12:
Line 13:
Line 14:
Line 15:
Line 16:
elements[j] = elements[index];
Line 17:
elements[index] = temp;
Line 18:
Line 19:
42
}
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Which of the following changes to the sort method would correctly sort the
integers in elements into descending order?
I. Replace line 9 with:
Line 9:
if (elements[k] > elements[index])
II.
III.
(a) I only
(b) II only
(c) I and II only
(d) I and III only
(e) I, II, and III
6a
11 c
16 b
21 d
2a
7a
12 e
17 d
22 d
3d
8c
13 c
18 a
23 c
4d
9d
14 d
19 d
24 e
5d
10 a
15 d
20 b
25 d
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
43
The declaration for the Time class is shown below. It includes a method
minutesUntil, which returns the difference (in minutes) between the current
Time object and another Time object.
For example, assume that t1 and t2 are Time objects where t1 represents
1:00 p.m. and t2 represents 2:15 p.m. The call t1.minutesUntil(t2) will
return 75 and the call t2.minutesUntil(t1) will return -75.
44
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
The declaration for the Flight class is shown below. It has methods to access the
departure time and the arrival time of a flight. You may assume that the departure
time of a flight is earlier than its arrival time.
public class Flight
{
/** @return time at which the flight departs
*/
public Time getDepartureTime()
{ /* implementation not shown */ }
A trip consists of a sequence of flights and is represented by the Trip class. The Trip
class contains a List of Flight objects that are stored in chronological order. You
may assume that for each flight after the first flight in the list, the departure time of the
flight is later than the arrival time of the preceding flight in the list. A partial declaration
of the Trip class is shown below. You will write two methods for the Trip class.
public class Trip
{
/** The list of flights (if any) that make up this trip, stored in chronological
order */
private List<Flight> flights;
/** @return the number of minutes from the departure of the first flight to the
*
arrival of the last flight if there are one or more flights in the trip;
*
0, if there are no flights in the trip
*/
public int getDuration()
{ /* to be implemented in part (a) */ }
Precondition: the departure time for each flight is later than the arrival
*
time of its preceding flight
*
@return the smallest number of minutes between the arrival of
*
a flight and the departure of the flight immediately after it,
*
if there are two or more flights in the trip;
*
-1, if there are fewer than two flights in the trip
*/
public int getShortestLayover()
{ /* to be implemented in part (b) */ }
/**
// There may be instance variables, constructors, and methods that are not
// shown.
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
45
For example, assume that the instance variable flights of a Trip object
vacation contains the following flight information.
Departure
Time
Arrival
Time
Flight
0
11:30 a.m.
12:15 p.m.
Flight
1
1:15 p.m.
Flight
2
4:00 p.m.
Flight
3
10:15 p.m.
Layover
(minutes)
} 60
3:45 p.m.
} 15
6:45 p.m.
} 210
11:00 p.m.
46
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
2. Consider the following incomplete StringUtil class declaration. You will write
implementations for the two methods listed in this class. Information about the
Person class used in the replaceNameNickname method will be presented in
part (b).
public class StringUtil
{
/** @param str a String with length > 0
* @param oldstr a String
* @param newstr a String
* @return a new String in which all occurrences of the substring
*
oldstr in str are replaced by the substring newstr
*/
public static String apcsReplaceAll(String str,
String oldStr,
String newStr)
{ /* to be implemented in part (a) */ }
/** @param str a String
* @param people a list of references to Person objects
* @return a copy of str modified so that each occurrence of a first
*
name in people is replaced by the corresponding nickname
*/
public static String replaceNameNickname(String str,
List<Person>
people)
{ /* to be implemented in part (b) */ }
// There may be methods that are not shown.
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
47
str
oldstr
newstr
String returned
Comment
"to be
or not
to be"
"to"
"2"
"2 be or not
2 be"
Each occurrence
of "to" in the
original string has
been replaced by
2
"advanced
calculus"
"math"
"science"
"advanced
calculus"
No change,
because the string
"math" was not in
the original string
"gogogo"
"go"
"gone"
"gonegonegone"
Each occurrence
of "go" in the
original string has
been replaced by
"gone"
"aaaaa"
"aaa"
"b"
"baa"
The first
occurrence of
"aaa" in the
original string has
been replaced by
"b"
48
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
(b) The following Person class contains information that includes a first (given) name
and a nickname for the person.
public class Person
{
/** @return the first name of this Person */
public String getFirstName()
{ /* implementation not shown */ }
/** @return the nickname of this Person */
public String getNickname()
{ /* implementation not shown */ }
// There may be instance variables, constructors, and methods not shown.
}
For example, assume the following table represents the data contained in the list
people.
getFirstName()
getNickname()
"Henry"
"Hank"
"Elizabeth"
"Liz"
"John"
"Jack"
"Margaret"
"Peggy"
"After Hank drove Liz to dinner in Jackson City, Hank paid for
an appetizer and Liz paid for dessert."
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
49
50
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Note that a Cat is-a Pet, a Dog is-a Pet, and a LoudDog is-a Dog.
The class Pet is specified as an abstract class as shown in the following
declaration. Each Pet has a name that is specified when it is constructed.
public abstract class Pet
{
private String name;
public Pet(String petName)
{ name = petName; }
public String getName()
{ return name; }
public abstract String speak();
}
The subclass Dog has the partial class declaration shown below.
public class Dog extends Pet
{
public Dog(String petName)
{ /* implementation not shown */
(a) Given the class hierarchy shown above, write a complete class declaration for
the class Cat, including implementations of its constructor and method(s).
The Cat method speak returns "meow" when it is invoked.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
51
(b) Assume that class Dog has been declared as shown at the beginning of
the question. If the String dog-sound is returned by the Dog method
speak, then the LoudDog method speak returns a String containing
dog-sound repeated two times.
/** For every Pet in the kennel, prints the name followed by
* the result of a call to its speak method, one line per Pet.
*/
public void allSpeak()
{ /* to be implemented in part (c) */ }
Write the Kennel method allSpeak. For each Pet in the kennel,
allSpeak prints a line with the name of the Pet followed by the result of
a call to its speak method.
In writing allSpeak, you may use any of the methods defined for any of
the classes specified for this problem. Assume that these methods work as
specified, regardless of what you wrote in parts (a) and (b).
52
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
11
After call
arr:
27
12
11
13
12
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
14
13
15
14
53
54
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
55
0
1
2
3
0
13
16
19
22
Before call
1
14
17
20
23
2
15
18
21
24
0
1
2
3
0
48
15
18
21
After call
1
13
16
19
22
2
14
17
20
23
56
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
(b)
public int getShortestLayover()
{
if (flights.size() < 2)
{
return -1;
}
int shortest = getDuration();
for (int k = 1; k < flights.size(); k++)
{
Flight flight1 = flights.get(k - 1);
Flight flight2 = flights.get(k);
Time arrive = flight1.getArrivalTime();
Time depart = flight2.getDepartureTime();
int layover = arrive.minutesUntil(depart);
if (layover < shortest)
{
shortest = layover;
}
}
return shortest;
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
57
Question 2
(a)
Iterative version:
public static String apcsReplaceAll(String str,
String oldStr,
String newStr)
{
String firstPart = "";
String lastPart = str;
int pos = lastPart.indexOf(oldStr);
while (pos >= 0)
{
firstPart += lastPart.substring(0, pos);
firstPart += newStr;
lastPart = lastPart.substring(pos + oldStr.length());
pos = lastPart.indexOf(oldStr);
}
return firstPart + lastPart;
}
Recursive version:
public static String apcsReplaceAll(String str,
String oldStr,
String newStr)
{
int pos = str.indexOf(oldStr);
if (pos < 0)
{
return str;
}
else
{
String firstPart = str.substring(0, pos);
String restOfStr = str.substring(pos + oldStr.length());
String lastPart = apcsReplaceAll(restOfStr, oldStr, newStr);
return firstPart + newStr + lastPart;
}
}
58
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
(b)
public static String replaceNameNickname(String str,
List<Person> people)
{
for (Person p : people)
{
str = apcsReplaceAll(str, p.getFirstName(), p.getNickname());
}
return str;
}
Question 3
(a)
public class Cat extends Pet
{
public Cat(String petName)
{ super(petName); }
public String speak()
{
return "meow";
}
}
(b)
public class LoudDog extends Dog
{
public LoudDog(String petName)
{ super(petName); }
public String speak()
{
return super.speak() + super.speak();
}
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
59
(c)
public void allSpeak()
{
for (Pet a : petList)
{
System.out.println(a.getName() + a.speak());
}
}
Question 4
(a)
public static void shiftArray(int[] arr, int num)
{
for (int k = arr.length 1; k > 0; k)
{
arr[k] = arr[k - 1];
}
arr[0] = num;
}
(b)
public void shiftMatrix(int num)
{
for (int[] row: matrix)
{
int temp = row[row.length 1];
ArrayUtil.shiftArray(row, num);
num = temp;
}
}
(c)
public void rotateMatrix()
{
shiftMatrix(matrix[matrix.length 1][matrix[0].length 1]);
}
60
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
APPENDIX A
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
61
Notes
Comments
Javadoc tool
Primitive Types
int,
double,
boolean
Operators
Arithmetic: +, , *, /, %
Increment/Decrement: ++,
Assignment: =, +=, =, *=,
1, 2, 3,
4, 5
/=, %=
Relational: ==, !=, <, <=,
>, >=
&, |, ^
(char), (float)
StringBuilder
Shift: <<, >>, >>>
Bitwise: ~, &, |, ^
Conditional: ?:
Logical: !, &&, ||
Numeric casts: (int), (double)
String concatenation: +
Object Comparison
object identity (==, !=) vs.
object equality (equals),
implementation of equals
String compareTo
Comparable
Escape Sequences
\", \\, \n inside strings
\, \t, \unnnn
Input / Output
System.out.print,
System.out.println
Scanner, System.in,
System.out, System.err,
Stream input/output,
GUI input/output,
parsing input: Integer.parseInt,
Double.parseDouble
formatting output:
System.out.printf
62
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Notes
Exceptions
try/catch/finally
throw, throws
assert
ArithmeticException,
NullPointerException,
IndexOutOfBoundsException,
ArrayIndexOutOfBoundsException,
IllegalArgumentException
Arrays
1-dimensional arrays,
2-dimensional rectangular arrays,
initializer list: { },
row-major order of
2-dimensional array elements
7, 8
new type[]{ } ,
ragged arrays (non-rectangular),
arrays with 3 or more dimensions
Control Statements
switch,
break, continue,
do-while
if, if/else,
while, for,
enhanced for (for-each),
return
Variables
parameter variables,
local variables,
private instance variables:
visibility (private)
static (class) variables:
visibility (public, private),
final
Methods
visibility (public, private),
static, non-static,
method signatures,
overloading, overriding,
parameter passing
9, 10
visibility (protected),
public static void
main(String[] args),
command line arguments,
variable number of parameters,
final
Constructors
11, 12
super(), super(args)
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
63
Notes
Classes
13, 14
final,
visibility (private, protected),
new,
visibility (public),
accessor methods,
modifier (mutator) methods
Design/create/modify class.
Create subclass of a superclass
(abstract, non-abstract).
Create class that implements an interface.
Interfaces
Design/create/modify an interface.
nested classes,
inner classes,
enumerations
13, 14
Inheritance
Understand inheritance hierarchies.
Design/create/modify subclasses.
Design/create/modify classes that
implement interfaces.
Packages
import packageName.* ,
static import,
package packageName ,
import packageName.className
class path
Miscellaneous OOP
is-a and has-a relationships,
15, 16
instanceof
(class) cast
this.var, this.method(args),
null,
this,
super.method(args)
Standard Java Librar y
17, 18
Object,
Integer, Double,
String,
Math,
List<E>, ArrayList<E>
64
clone,
autoboxing,
Collection<E>,
Arrays, Collections
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Notes
1. Students are expected to understand the operator precedence rules of the listed
operators.
2. The increment/decrement operators ++ and are part of the AP Java subset.
These operators are used only for their side effect, not for their value. That is,
the postfix form (for example, x++) is always used, and the operators are not
used inside other expressions. For example, arr[x++] is not used.
3. Students need to understand the short circuit evaluation of the && and ||
operators.
4. Students are expected to understand truncation towards 0 behavior as well
as the fact that positive floating-point numbers can be rounded to the nearest
integer as
negative numbers as (int)(x 0.5).
5. String concatenation + is part of the AP Java subset. Students are expected to know
that concatenation converts numbers to strings and invokes toString on objects.
6. User input is not included in the AP Java subset. There are many possible ways for
supplying user input: e.g., by reading from a Scanner, reading from a stream (such
as a file or a URL), or from a dialog box. There are advantages and disadvantages to
the various approaches. The exam does not prescribe any one approach. Instead, if
reading input is necessary, it will be indicated in a way similar to the following:
or
double x = ...;
7. Both arrays of primitive types (e.g., int[], int[][]) and arrays of objects
(e.g., Student[], Student[][]) are in the subset.
8. Students need to understand that 2-dimensional arrays are stored as arrays of
arrays. For the purposes of the AP CS A Exam, students should assume that
2-dimensional arrays are rectangular (not ragged) and the elements are indexed
in row-major order. For example, given the declaration
int[][] m = {{1, 2, 3}, {4, 5, 6}};
m.length is 2 (the number of rows), m[0].length is 3 (the number of
columns), m[r][c] represents the element at row r and column c, and
m[r] represents row r (e.g., m[0] is of type int[] and references the
array {1, 2, 3}).
Students are expected to be able to access a row of a 2-dimensional array, assign
it to a 1-dimensional array reference, pass it as a parameter, and use loops
(including for-each) to traverse the rows. However, students are not expected to
analyze or implement code that replaces an entire row in a 2-dimensional array,
such as
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
65
9. The main method and command-line arguments are not included in the subset.
In free-response questions, students are not expected to invoke programs. In the
AP Computer Science Labs, program invocation with main may occur, but the
main method will be kept very simple.
10. Students are required to understand when the use of static methods is
appropriate. In the exam, static methods are always invoked through a
class (explicitly or implicitly), never an object (i.e., ClassName.staticMethod( ) or
staticMethod( ), not obj.staticMethod( )).
11. If a subclass constructor does not explicitly invoke a superclass constructor, the
Java compiler automatically inserts a call to the no-argument constructor of the
superclass.
12. Students are expected to implement constructors that initialize all instance
variables. Class constants are initialized with an initializer:
public static final int MAX_SCORE = 5;
The rules for default initialization (with 0, false or null) are not included
in the subset. Initializing instance variables with an initializer is not included in
the subset. Initialization blocks are not included in the subset.
13. Students are expected to write interfaces or class declarations when given a
general description of the interface or class.
14. Students are expected to extend classes and implement interfaces. Students are
also expected to have knowledge of inheritance that includes understanding the
concepts of method overriding and polymorphism. Students are expected to
implement their own subclasses.
Students are expected to read the definition of an abstract class and understand
that the abstract methods need to be implemented in a subclass. Students are
similarly expected to read the definition of an interface and understand that the
abstract methods need to be implemented in an implementing class.
15. Students are expected to understand that conversion from a subclass reference
to a superclass reference is legal and does not require a cast. Class casts
(generally from Object to another class) are not included in the AP Java
subset. Array type compatibility and casts between array types are not included
in the subset.
16. The use of this is restricted to passing the implicit parameter in its entirety
to another method (e.g., obj.method(this)) and to descriptions such as the
implicit parameter this". Students are not required to know the idiom
"this.var = var, where var is both the name of an instance variable and a
parameter variable.
17. The use of generic collection classes and interfaces is in the AP Java subset, but
students need not implement generic classes or methods.
18. Students are expected to know a subset of the constants and methods of the
listed Standard Java Library classes and interfaces. Those constants and methods
are enumerated in the Java Quick Reference (Appendix B).
66
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
APPENDIX B
String toString()
class java.lang.Integer
Integer(int value)
int intValue()
Integer.MIN_VALUE
Integer.MAX_VALUE
class java.lang.Double
Double(double value)
double doubleValue()
class java.lang.String
int length()
class java.lang.Math
int size()
E get(int index)
E set(int index, E obj)
E remove(int index)
//
//
//
//
//
//
//
//
//
//
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
67
Sequential Search
The Sequential Search Algorithm below finds the index of a value in an array of
integers as follows:
1. Traverse elements until target is located, or the end of elements is
reached.
2. If target is located, return the index of target in elements;
Otherwise return 1.
/**
* Finds the index of a value in an array of integers.
*
* @param elements an array containing the items to be searched.
* @param target the item to be found in elements.
* @return an index of target in elements if found; -1 otherwise.
*/
public static int sequentialSearch(int[] elements, int target)
{
for (int j = 0; j < elements.length; j++)
{
if (elements[j] == target)
{
return j;
}
}
return 1;
68
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Binary Search
The Binary Search Algorithm below finds the index of a value in an array of
integers sorted in ascending order as follows:
1. Set left and right to the minimum and maximum indexes of elements
respectively.
2. Loop until target is found, or target is determined not to be in elements
by doing the following for each iteration:
a. Set middle to the index of the middle item in elements[left] ...
elements[right] inclusive.
b. If target would have to be in elements[left] ... elements[middle
- 1] inclusive, then set right to the maximum index for that range.
c. Otherwise, if target would have to be in elements[middle + 1] ...
elements[right] inclusive, then set left to the minimum index for that
range.
d. Otherwise, return middle because target == elements[middle].
3. Return -1 if target is not contained in elements.
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
69
/**
* Find the index of a value in an array of integers sorted in ascending order.
*
* @param elements an array containing the items to be searched.
*
Precondition: items in elements are sorted in ascending order.
* @param target the item to be found in elements.
* @return an index of target in elements if target found;
*
-1 otherwise.
*/
public static int binarySearch(int[] elements, int target)
{
int left = 0;
int right = elements.length 1;
while (left <= right)
{
int middle = (left + right) / 2;
if (target < elements[middle])
{
right = middle 1;
}
else if (target > elements[middle])
{
left = middle + 1;
}
else
{
return middle;
}
}
return 1;
}
70
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Selection Sort
The Selection Sort Algorithm below sorts an array of integers into ascending order
as follows:
1. Loop from j = 0 to j = elements.length2, inclusive, completing
elements.length1 passes.
2. In each pass, swap the item at index j with the minimum item in the rest of the
array (elements[j+1] through elements[elements.length1]).
At the end of each pass, items in elements[0] through elements[j] are in
ascending order and each item in this sorted portion is at its final position in the array
/**
* Sort an array of integers into ascending order.
*
* @param elements an array containing the items to be sorted.
*
* Postcondition: elements contains its original items and items in elements
*
are sorted in ascending order.
*/
public static void selectionSort(int[] elements)
{
for (int j = 0; j < elements.length 1; j++)
{
int minIndex = j;
for (int k = j + 1; k < elements.length; k++)
{
if (elements[k] < elements[minIndex])
{
minIndex = k;
}
}
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp;
}
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
71
Insertion Sort
The Insertion Sort Algorithm below sorts an array of integers into ascending order
as follows:
1. Loop from j = 1 to j = elements.length1 inclusive, completing
elements.length1 passes.
2. In each pass, move the item at index j to its proper position in elements[0]
to elements[j]:
a. Copy item at index j to temp, creating a vacant element at index j
(denoted by possibleIndex).
b. Loop until the proper position to maintain ascending order is found for temp.
c. In each inner loop iteration, move the vacant element one position lower in
the array.
3. Copy temp into the identified correct position (at possibleIndex).
At the end of each pass, items at elements[0] through elements[j] are in
ascending order.
/**
* Sort an array of integers into ascending order.
*
* @param elements an array containing the items to be sorted.
*
* Postcondition: elements contains its original items and items in elements
*
are sorted in ascending order.
*/
public static void insertionSort(int[] elements)
{
for (int j = 1; j < elements.length; j++)
{
int temp = elements[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp < elements[possibleIndex 1])
{
elements[possibleIndex] = elements[possibleIndex 1];
possibleIndex;
}
elements[possibleIndex] = temp;
}
}
72
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
Merge Sort
The Merge Sort Algorithm below sorts an array of integers into ascending order as
follows:
mergeSort
This top-level method creates the necessary temporary array and calls the
mergeSortHelper recursive helper method.
mergeSortHelper
This recursive helper method uses the Merge Sort Algorithm to sort
elements[from] ... elements[to] inclusive into ascending order:
1. If there is more than one item in this range,
a. divide the items into two adjacent parts, and
b. call mergeSortHelper to recursively sort each part, and
c. call the merge helper method to merge the two parts into sorted order.
2. Otherwise, exit because these items are sorted.
merge
This helper method merges two adjacent array parts, each of which has been sorted
into ascending order, into one array part that is sorted into ascending order:
1. As long as both array parts have at least one item that hasnt been copied,
compare the first un-copied item in each part and copy the minimal item to the
next position in temp.
2. Copy any remaining items of the first part to temp.
3. Copy any remaining items of the second part to temp.
4. Copy the items from temp[from] ... temp[to] inclusive to the respective
locations in elements.
/**
* Sort an array of integers into ascending order.
*
* @param elements an array containing the items to be sorted.
*
* Postcondition: elements contains its original items and items in elements
*
are sorted in ascending order.
*/
public static void mergeSort(int[] elements)
{
int n = elements.length;
int[] temp = new int[n];
mergeSortHelper(elements, 0, n 1, temp);
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
73
/**
* Sorts elements[from] ... elements[to] inclusive into ascending order.
*
* @param elements an array containing the items to be sorted.
* @param from the beginning index of the items in elements to be sorted.
* @param to the ending index of the items in elements to be sorted.
* @param temp a temporary array to use during the merge process.
*
* Precondition:
*
(elements.length == 0 or
*
0 <= from <= to <= elements.length) and
*
elements.length == temp.length
* Postcondition: elements contains its original items and the items in elements
[from] ... <= elements[to] are sorted in ascending order.
*
*/
private static void mergeSortHelper(int[] elements,
int from, int to, int[] temp)
{
if (from < to)
{
int middle = (from + to) / 2;
mergeSortHelper(elements, from, middle, temp);
mergeSortHelper(elements, middle + 1, to, temp);
merge(elements, from, middle, to, temp);
}
}
74
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
/**
* Merges two adjacent array parts, each of which has been sorted into ascending
* order, into one array part that is sorted into ascending order.
*
* @param elements an array containing the parts to be merged.
* @param from the beginning index in elements of the first part.
* @param mid the ending index in elements of the first part.
*
mid+1 is the beginning index in elements of the second part.
* @param to the ending index in elements of the second part.
* @param temp a temporary array to use during the merge process.
*
* Precondition: 0 <= from <= mid <= to <= elements.length and
*
elements[from] ... <= elements[mid] are sorted in ascending order and
*
elements[mid + 1] ... <= elements[to] are sorted in ascending order and
*
elements.length == temp.length
* Postcondition: elements contains its original items and
*
elements[from] ... <= elements[to] are sorted in ascending order and
*
elements[0] ... elements[from 1] are in original order and
*
elements[to + 1] ... elements[elements.length 1] are in original order.
*/
private static void merge(int[] elements,
int from, int mid, int to, int[] temp)
{
int i = from;
int j = mid + 1;
int k = from;
while (i <= mid && j <= to)
{
if (elements[i] < elements[j])
{
temp[k] = elements[i];
i++;
}
else
{
temp[k] = elements[j];
j++;
}
k++;
}
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
75
76
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
AP Course Audit
Curricular/resource requirements
Four annotated sample syllabi
Syllabus development guides
Example textbook lists
Syllabus development tutorial
Advances in AP
Learn about forthcoming changes to AP courses
AP Teacher Communities
Join a lively community of fellow teachers by discussing all things AP on the
discussion boards. Share strategies, ask questions, and engage in lively discussions
with teachers worldwide.
Higher Ed
Detailed information about each course and exam
An overview of the course and exam redesign and what it means for colleges and
universities
Information about the new AP | Cambridge Capstone Program pilot
Research reports on AP students performance in subsequent college course and
their progress towards a degree
Guides and resources for effective policy review
Promising practices in admission and policy-setting
2014 The College Board. Visit the College Board on the Web: www.collegeboard.org.
77
Contact Us
New York Office
250 Vesey Street
New York, NY 10281
212-713-8000
212-713-8277/55 (Fax)
AP Services
P.O. Box 6671
Princeton, NJ 08541-6671
609-771-7300
888-225-5427 (toll free in the U.S. and Canada)
610-290-8979 (Fax)
Email: apexams@info.collegeboard.org
AP Canada Office
2950 Douglas Street, Suite 550
Victoria, BC, Canada V8T 4N4
250-472-8561
800-667-4548 (toll free in Canada only)
Email: gewonus@ap.ca
International Services
Serving all countries outside the U.S. and Canada
250 Vesey Street
New York, NY 10281
212-373-8738
Email: international@collegeboard.org
apcentral.collegeboard.org
I.N. 120085144