Java Array Programs for SDET Sort

Array programs are the backbone of Java coding rounds: sort without a built-in method, reverse in place, find duplicates, count frequencies. Interviewers usually ask for a simple version, then "can you make it faster?", then an edge case. Every program here was compiled and run — the outputs are real — and each shows both the approach interviewers expect and the efficient one. More array programs: rotation, missing number and pair sum and basics and calculations.

The sample array used below: int[] arr = {2, 4, 5, 2, 7, 4, 9, 4}; — note that 4 appears three times, which exposes a common bug.

Advertisement

1. Bubble Sort (Ascending) ⭐

static void bubbleSort(int[] a) {
    for (int i = 0; i < a.length - 1; i++) {
        boolean swapped = false;
        for (int j = 0; j < a.length - 1 - i; j++) {        // the last i items are already in place
            if (a[j] > a[j + 1]) {
                int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
                swapped = true;
            }
        }
        if (!swapped) break;                                // no swaps → already sorted
    }
}
// {45, 12, 78, 3, 25} → [3, 12, 25, 45, 78]

Each pass "bubbles" the largest remaining value to the end. The swapped flag is the improvement interviewers look for: an already-sorted array finishes after one pass, O(n), instead of O(n²). Worst case remains O(n²) — in real code use Arrays.sort() (a tuned O(n log n) algorithm).

2. Sort Descending

Flip the comparison in bubble sort (a[j] < a[j + 1]), or with the library:

Integer[] d = {45, 12, 78, 3, 25};
Arrays.sort(d, Collections.reverseOrder());    // [78, 45, 25, 12, 3]

Collections.reverseOrder() needs an Integer[], not an int[] — comparators don't work on primitive arrays. For int[], sort ascending and then reverse (next program).

3. Reverse an Array in Place

static void reverse(int[] a) {
    for (int i = 0, j = a.length - 1; i < j; i++, j--) {
        int t = a[i]; a[i] = a[j]; a[j] = t;
    }
}
// {10, 20, 30, 40, 50} → [50, 40, 30, 20, 10]

Two pointers swap from both ends and meet in the middle: O(n) time, O(1) extra space, no second array.

4. Find Duplicate Elements ⭐

The brute-force version compares every pair with nested loops — O(n²). The efficient version uses a HashSet, whose add() returns false for a value it already holds. But the version found in many tutorials has a bug:

Set<Integer> set = new HashSet<>();
for (int n : arr) if (!set.add(n)) System.out.println(n);
// prints 2, 4, 4   ← 4 is reported twice because it appears three times

Collect duplicates in a second set so each is reported once:

static Set<Integer> duplicates(int[] a) {
    Set<Integer> seen = new HashSet<>(), dups = new LinkedHashSet<>();
    for (int n : a) if (!seen.add(n)) dups.add(n);
    return dups;
}
// {2, 4, 5, 2, 7, 4, 9, 4} → [2, 4]

O(n) time, O(n) space. LinkedHashSet keeps the order in which duplicates were found.

5. Remove Duplicates (Keep Order)

static int[] removeDuplicates(int[] a) {
    return new LinkedHashSet<>(Arrays.stream(a).boxed().toList())
            .stream().mapToInt(Integer::intValue).toArray();
}
// → [2, 4, 5, 7, 9]

Or Arrays.stream(a).distinct().toArray() — also order-preserving. For a sorted array, a two-pointer pass removes duplicates in O(1) extra space, a common follow-up.

6. Count the Frequency of Each Element

static Map<Integer, Integer> frequency(int[] a) {
    Map<Integer, Integer> f = new LinkedHashMap<>();
    for (int n : a) f.merge(n, 1, Integer::sum);
    return f;
}
// → {2=2, 4=3, 5=1, 7=1, 9=1}

One pass, O(n). The older approach with a visited[] boolean array and nested loops works without collections but is O(n²) — mention it if the interviewer says "no HashMap". Streams version: Arrays.stream(a).boxed().collect(Collectors.groupingBy(x -> x, LinkedHashMap::new, Collectors.counting())).

7. Unique Elements, First Duplicate, First Non-Repeating

static List<Integer> unique(int[] a) {
    return frequency(a).entrySet().stream()
            .filter(e -> e.getValue() == 1).map(Map.Entry::getKey).toList();
}
// → [5, 7, 9]

static Integer firstDuplicate(int[] a) {
    Set<Integer> seen = new HashSet<>();
    for (int n : a) if (!seen.add(n)) return n;
    return null;                                   // no duplicates
}
// → 2  (the first value seen for a second time)

static Integer firstNonRepeating(int[] a) {
    for (Map.Entry<Integer, Integer> e : frequency(a).entrySet())
        if (e.getValue() == 1) return e.getKey();
    return null;
}
// → 5

The LinkedHashMap in frequency() is what makes "first" meaningful — a HashMap has no reliable order.

8. Move All Zeros to the End

static void moveZerosToEnd(int[] a) {
    int pos = 0;
    for (int n : a) if (n != 0) a[pos++] = n;     // compact the non-zero values
    while (pos < a.length) a[pos++] = 0;          // fill the rest with zeros
}
// {0, 1, 0, 3, 12} → [1, 3, 12, 0, 0]

O(n), in place, and the non-zero values keep their order.

9. Merge Two Sorted Arrays

static int[] mergeSorted(int[] x, int[] y) {
    int[] out = new int[x.length + y.length];
    int i = 0, j = 0, k = 0;
    while (i < x.length && j < y.length) out[k++] = x[i] <= y[j] ? x[i++] : y[j++];
    while (i < x.length) out[k++] = x[i++];
    while (j < y.length) out[k++] = y[j++];
    return out;
}
// {1, 4, 9} + {2, 3, 10, 11} → [1, 2, 3, 4, 9, 10, 11]

O(n + m) — the merge step of merge sort, and a favorite follow-up after sorting questions.

10. Check Whether an Array Is Sorted

static boolean isSortedAscending(int[] a) {
    for (int i = 1; i < a.length; i++) if (a[i] < a[i - 1]) return false;
    return true;
}
isSortedAscending: [1, 2, 2, 5] true, [1, 3, 2] false, [] true

Compare each element with the one before it and stop at the first drop — O(n), no sorting needed. Equal neighbors are allowed (non-decreasing order). In UI automation this is the check behind "sort by price" tests: read the prices from the page into an array and assert it's sorted.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

Complexity Summary

Program Time Extra space
Bubble sort O(n²) worst, O(n) if already sorted O(1)
Arrays.sort O(n log n) Small
Reverse, move zeros O(n) O(1)
Duplicates / frequency with nested loops O(n²) O(1)–O(n)
Duplicates / frequency / unique with Set or Map O(n) O(n)
Merge two sorted arrays O(n + m) O(n + m)

Step through bubble sort and the two-pointer reverse line by line — watching the indexes and swaps — in the Java Code Visualizer.

From the Interview Room

My automation work has been in Java — Selenium WebDriver scripts with TestNG in Eclipse — and I use OOP concepts such as classes and objects, method overloading, overriding and constructors in page classes and utilities. Small programs like this one are the building blocks of real framework code: looping through data, comparing expected and actual values, and handling edge cases. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. A HashMap turns most frequency and duplicate problems into a single pass.

📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation

Frequently Asked Questions

How do you find duplicates in an array efficiently?

Loop once with a HashSet: when add() returns false the value is a duplicate. Add it to a second set so values that appear three or more times are reported once. O(n) time.

How do you reverse an array without another array?

Two pointers from both ends, swapping and moving inward until they meet — O(n) time, O(1) space.

How does bubble sort work?

It compares neighbors and swaps them when out of order; each pass moves the largest remaining value to the end. Stop early when a pass makes no swaps.

How do you count element frequencies?

With a LinkedHashMap and merge(n, 1, Integer::sum) in one pass, or with nested loops and a visited array if collections aren't allowed.

How do you sort an int array in descending order?

Box it to Integer[] and use Arrays.sort(arr, Collections.reverseOrder()), or sort ascending and reverse in place.