Common Array Algorithms

Reverse and Search

Example

These small algorithms come up again and again in coding tests.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 1, 9, 2};

        // reverse in place with two pointers
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int tmp = arr[left];
            arr[left] = arr[right];
            arr[right] = tmp;
            left++;
            right--;
        }
        System.out.println("Reversed: " + Arrays.toString(arr));

        // linear search
        int key = 8, pos = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) { pos = i; break; }
        }
        System.out.println(key + " found at index " + pos);
    }
}

Output

Reversed: [2, 9, 1, 8, 3, 5]
8 found at index 3

Bubble Sort

Example

Bubble sort repeatedly swaps neighbours that are in the wrong order. Use Arrays.sort in real code, but know how sorting works.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {64, 25, 12, 22, 11};
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int t = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = t;
                }
            }
            System.out.println("Pass " + (i + 1) + ": " + Arrays.toString(a));
        }
    }
}

Output

Pass 1: [25, 12, 22, 11, 64]
Pass 2: [12, 22, 11, 25, 64]
Pass 3: [12, 11, 22, 25, 64]
Pass 4: [11, 12, 22, 25, 64]

Second Largest

Example

public class Main {
    public static void main(String[] args) {
        int[] nums = {12, 35, 1, 10, 34, 35};
        int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
        for (int n : nums) {
            if (n > first) {
                second = first;
                first = n;
            } else if (n > second && n != first) {
                second = n;
            }
        }
        System.out.println("Largest: " + first + ", Second largest: " + second);
    }
}

Output

Largest: 35, Second largest: 34

Exercise: Write code that checks whether int[] a is sorted in ascending order.

Show answer
boolean sorted = true;
for (int i = 1; i < a.length; i++) {
    if (a[i] < a[i - 1]) { sorted = false; break; }
}
System.out.println(sorted);