1 min read•june 18, 2024
Avanish Gupta
Milo Chang
Avanish Gupta
Milo Chang
One of the main applications of ArrayLists is to search, that is to see if an element is actually in an and to return its index if it is.
The simplest searching algorithm, and the only one we will learn in this unit, is . 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.
Here is its implementation for an ArrayList:
public static int linearSearch(ArrayList
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 covered in Unit 10.