πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ’Ύ

7.5 Searching

1 min readβ€’june 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Linear / Sequential Search

One of the main applications of ArrayLists is to search, that is to see if an element is actually in an ArrayList and to return its index if it is.
The simplest searching algorithm, and the only one we will learn in this unit, is linear/sequential search. This algorithm goes through the list element by element (thus the names sequential and linear) until the element is found. If the element is not found, -1 is returned.

ArrayList Implementation

Here is its implementation for an ArrayList:
public static int linearSearch(ArrayList<Integer> array, int n) { for (int i = 0; i < array.size(); i++) { if (array.get(i) == n) { return i; } } return -1; }

Integer Array Implementation

Here is the implementation for a regular integer array:
public static int linearSearch(int[] array, int n) { for (int i = 0; i < array.length; i++) { if (array[i] == n) { return i; } } return -1; }
There are other searching algorithms, but the only other important one to know is binary search covered in Unit 10.
Browse Study Guides By Unit
βž•Unit 1 – Primitive Types
πŸ“±Unit 2 – Using Objects
πŸ–₯Unit 3 – Boolean Expressions & if Statements
πŸ•ΉUnit 4 – Iteration
βš™οΈUnit 5 – Writing Classes
⌚️Unit 6 – Array
πŸ’ΎUnit 7 – ArrayList
πŸ’»Unit 8 – 2D Array
πŸ–²Unit 9 – Inheritance
πŸ–±Unit 10 – Recursion
🧐Exam Skills

Fiveable
Fiveable
Home
Stay Connected

Β© 2024 Fiveable Inc. All rights reserved.


Β© 2024 Fiveable Inc. All rights reserved.