Traversal, Insertion, Deletion The Truth About Array Performance

java dev.to


Arrays look simple… but the way operations behave on them can make or break your performance.

Why is accessing an element instant, but inserting in the middle slow?

Let’s break it down in the simplest way possible.

1. Traversal (Visiting Elements)

Traversal means visiting each element one by one.

for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

// Enhanced loop
for (int num : arr) {
System.out.println(num);
}

Time Complexity: O(n)

  • You must visit every element
  • No shortcut possible

2. Insertion
Case 1: Insert at End

  • If space is available → O(1)
  • Just place the element

Case 2: Insert at Middle

public static void insert(int[] arr, int pos, int value) {
for (int i = arr.length - 1; i > pos; i--) {
arr[i] = arr[i - 1];
}
arr[pos] = value;
}

Time Complexity: O(n)

Why slow?
Because elements need to shift right

3. Deletion

Case 1: Delete from End
Simply remove → O(1)

Case 2: Delete from Middle

public static void delete(int[] arr, int pos) {
for (int i = pos; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
}

Time Complexity: O(n)

Again, shifting required (left side)

The Real Insight

  • Arrays are fast for reading
  • But slow for modifying in the middle

Because of one reason:

Shifting elements = extra work = O(n)

Key Insights

  • Traversal → O(n)
  • Insert at end → O(1)
  • Insert in middle → O(n)
  • Delete from end → O(1)
  • Delete from middle → O(n)

For More: https://www.quipoin.com/tutorial/data-structure-with-java/array-operations

Source: dev.to

arrow_back Back to Tutorials