Array Operations
Traversal, searching, sorting
Interview Relevant: Searching and sorting algorithms are interview essentials
8 min read
Essential Array Operations
Arrays support several fundamental operations that every Java developer should master.
Operation Categories
- Traversal: Visiting each element
- Searching: Finding elements (linear, binary)
- Sorting: Arranging elements in order
- Manipulation: Insert, delete, reverse, rotate
💡 Performance Tip: Linear search is O(n), binary search is O(log n) but requires sorted array. Choose wisely based on your data!
Time Complexities
| Operation | Time Complexity |
|---|---|
| Access by index | O(1) |
| Linear search | O(n) |
| Binary search | O(log n) |
| Arrays.sort() | O(n log n) |
Code Examples
Linear and binary search implementations
java
1// Linear Search
2public static int linearSearch(int[] arr, int target) {
3 for (int i = 0; i < arr.length; i++) {
4 if (arr[i] == target) {
5 return i; // Return index if found
6 }
7 }
8 return -1; // Not found
9}
10
11// Usage
12int[] numbers = {5, 2, 8, 1, 9, 3};
13int index = linearSearch(numbers, 8);
14System.out.println("Found at index: " + index); // 2
15
16// Binary Search (array must be sorted!)
17public static int binarySearch(int[] arr, int target) {
18 int left = 0, right = arr.length - 1;
19
20 while (left <= right) {
21 int mid = left + (right - left) / 2; // Avoid overflow
22
23 if (arr[mid] == target) return mid;
24 else if (arr[mid] < target) left = mid + 1;
25 else right = mid - 1;
26 }
27 return -1; // Not found
28}Built-in and manual sorting methods
java
1// Sorting arrays
2int[] arr = {5, 2, 8, 1, 9, 3};
3
4// Built-in sort (modifies original)
5Arrays.sort(arr);
6System.out.println(Arrays.toString(arr)); // [1, 2, 3, 5, 8, 9]
7
8// Sort in descending order
9Integer[] nums = {5, 2, 8, 1, 9, 3};
10Arrays.sort(nums, Collections.reverseOrder());
11System.out.println(Arrays.toString(nums)); // [9, 8, 5, 3, 2, 1]
12
13// Bubble Sort (manual implementation)
14public static void bubbleSort(int[] arr) {
15 int n = arr.length;
16 for (int i = 0; i < n - 1; i++) {
17 for (int j = 0; j < n - i - 1; j++) {
18 if (arr[j] > arr[j + 1]) {
19 // Swap
20 int temp = arr[j];
21 arr[j] = arr[j + 1];
22 arr[j + 1] = temp;
23 }
24 }
25 }
26}Array reversal and rotation algorithms
java
1// Array reversal
2public static void reverse(int[] arr) {
3 int left = 0, right = arr.length - 1;
4 while (left < right) {
5 // Swap
6 int temp = arr[left];
7 arr[left] = arr[right];
8 arr[right] = temp;
9 left++;
10 right--;
11 }
12}
13
14// Array rotation (rotate left by k positions)
15public static void rotateLeft(int[] arr, int k) {
16 k = k % arr.length; // Handle k > length
17 reverse(arr, 0, k - 1);
18 reverse(arr, k, arr.length - 1);
19 reverse(arr, 0, arr.length - 1);
20}
21
22// Helper for rotation
23private static void reverse(int[] arr, int start, int end) {
24 while (start < end) {
25 int temp = arr[start];
26 arr[start++] = arr[end];
27 arr[end--] = temp;
28 }
29}
30
31// Usage
32int[] nums = {1, 2, 3, 4, 5};
33rotateLeft(nums, 2);
34System.out.println(Arrays.toString(nums)); // [3, 4, 5, 1, 2]Common interview operations
java
1// Finding duplicates
2public static void findDuplicates(int[] arr) {
3 Set<Integer> seen = new HashSet<>();
4 Set<Integer> duplicates = new HashSet<>();
5
6 for (int num : arr) {
7 if (!seen.add(num)) {
8 duplicates.add(num);
9 }
10 }
11 System.out.println("Duplicates: " + duplicates);
12}
13
14// Remove duplicates (keep order)
15public static int[] removeDuplicates(int[] arr) {
16 Set<Integer> seen = new LinkedHashSet<>();
17 for (int num : arr) {
18 seen.add(num);
19 }
20 return seen.stream().mapToInt(Integer::intValue).toArray();
21}
22
23// Find second largest
24public static int secondLargest(int[] arr) {
25 int first = Integer.MIN_VALUE;
26 int second = Integer.MIN_VALUE;
27
28 for (int num : arr) {
29 if (num > first) {
30 second = first;
31 first = num;
32 } else if (num > second && num != first) {
33 second = num;
34 }
35 }
36 return second;
37}Use Cases
- Data retrieval and lookup
- Sorting data for display or processing
- Finding min/max values
- Removing duplicates
- Array manipulation in algorithms
- Data validation and filtering
Common Mistakes to Avoid
- Binary search on unsorted array
- Off-by-one errors in search bounds
- Modifying array during iteration
- Integer overflow in mid calculation
- Not handling empty arrays
- Forgetting to return -1 for not found