Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Sequential Search
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Let's dive into search functionality. Sequential search is a basic form of searching that checks if an element is present in a given list. This method will return a value telling us whether or not the searched value is in the given list. Take a look at the code below, where we have a method that searches through the array for integer '4'.
SequentialSearchExample.java
package exlcode;
public class SequentialSearchExample {
public static void main(String[] args) {
int[] exampleVariableOne = {2, 9, 6, 7, 4, 5, 3, 0, 1};
int target = 4;
sequentialSearch(exampleVariableOne, target);
}
public static void sequentialSearch(int[] parameterOne, int parameterTwo) {
int index = -1;
// searches each index of the array until it reaches the last index
for (int i = 0; i < parameterOne.length; i++) {
if (parameterOne[i] == parameterTwo) {
// if the target is found, int index is set as the value of i and
// the for loop is terminated
index = i;
break;
}
}
if (index == -1) {
System.out.println("Your target integer does not exist in the array");
} else {
System.out.println("Your target integer is in index " + index + " of the array");
}
}
}
The sequential search uses a concept we have already mastered, for or while loops that search for a specified integer in an array. The concept is called "sequential search" as it goes through the elements starting from the first one, indexed "0", all the way through to the final index. Once the search runs, it returns the index of the targeted value if the targeted value exists in the array. This search functionality can be used on any type of "array" or ArrayList, but it may not be your preferred way of searching once you learn about other search methods in the future.