Skip to main content

1D Arrays

An array is a linear data structure that stores elements of the same data type in contiguous memory locations. It is the simplest and most widely used data structure.

Properties of Arrays

  • Contiguous Memory: Array elements are stored right next to each other.
  • Fixed Size: In Java, once initialized, the size of an array cannot change.
  • Index Based: Elements are accessed via their integer index starting at 0.

Memory Layout

(Indices: [0] -> 10, [1] -> 20, [2] -> 30, [3] -> 40, [4] -> 50)

Operations & Time Complexity

OperationBest CaseWorst Case (Time)Description
AccessO(1)O(1)Accessing via arr[index]
SearchO(1)O(n)Linear search through elements
InsertO(1)O(n)Inserting at end O(1), shifting elements O(n)
DeleteO(1)O(n)Removing at end O(1), shifting elements O(n)

Implementation in Java

public class ArrayExample {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = new int[5]; // Array of size 5

// Insertion (O(1))
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

// Literal Initialization
int[] moreNumbers = {10, 20, 30, 40, 50};

// Traversal (O(n))
for (int i = 0; i < moreNumbers.length; i++) {
System.out.println("Element at index " + i + ": " + moreNumbers[i]);
}
}
}