Search⌘ K
AI Features

Traversal and Searching in an Array

Explore array traversal techniques and learn to implement linear and binary search algorithms in Java. Understand when to use each search method based on array order and analyze their time complexities for better coding efficiency.

At this point, the core array operations are established. Reading or updating a single element is only one aspect. Effective use of arrays also requires traversing them and locating elements. This lesson covers traversal and searching, which are fundamental operations in array-based problems.

Traversal (Iterate through the array)

Traversal means going through every element of an array, one at a time, from the first to the last. It is a commonly used operation and serves as the foundation for almost everything else: searching for a value, adding up a total, printing every element, or checking whether a condition is met.

How traversal works

To traverse an array, we use a loop that visits each element one at a time, from start to end. Think of it like reading through our scorecard from game 1 to the last game, one row at a time. We do not skip any entry and we do not jump ahead. We simply go through each one in order.

The most common way to traverse an array is with a for-each loop, where element is the current item being accessed from the array during each iteration. This allows us to process every value one by one without manually managing indices.

for (int element : array) {
// do something with element
}

Consider a scores array [88, 95, 70, 82, 91]. The following illustration shows how the loop visits each element one at a time from left to right:

Java implementation

The following code shows how to traverse the scores array and print each element:

Java 25
public class Main {
public static void main(String[] args) {
int[] scores = {88, 95, 70, 82, 91};
for (int score : scores) {
System.out.println(score);
}
}
}
Traversing an array

The loop goes through the scorecard from game 1 to game 5, printing each score in the order it was recorded. Unlike access or update, which go straight to one position, traversal visits every element in sequence. The larger the array, the longer it takes.

Sorted and unsorted arrays

Before we look at how we search through an array, it helps to understand that arrays can be of two types: unsorted or sorted.

  • An unsorted array has no particular order. The elements appear in whatever order they were added. Our scores array [88, 95, 70, 82, 91] is a good example: the scores were ...