Skip to main content
2 of 4
added 38 characters in body
Maksim Dmitriev
  • 1.4k
  • 2
  • 15
  • 29

Testing the Dutch national flag task

I recently coded the Dutch national flag problem in Java and wrote some tests. The array in zero-indexed. Please take a look at how I verify that elements of the output array are in the right order. It's the method verifyDutch

The Dutch national flag problem

public static void dutchFlag(int[] input, int mid) {
    if (input == null || input.length < 2) {
        return;
    }
    int i = 0; // the end of the red region
    int j = 0; // the element under consideration
    int k = input.length - 1; // the start of the blue region
    while (j <= k) {
        if (input[j] < mid) {
            swap(input, i, j);
            i++;
            j++;
        } else if (input[j] == mid) {
            j++;
        } else {
            swap(input, j, k);
            k--;
        }
    }
}

Testing

public class FlagSortsTests {

    @Test
    public void testDutchWithRandom() {
        int[] input = new int[10];
        Random random = new Random();
        for (int i = 0; i < input.length; i++) {
            input[i] = random.nextInt(100);
        }
        int mid = input[random.nextInt(input.length - 1)];
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    @Test
    public void testDutchSmallestMid() {
        int[] input = { 12, 34, 781, -1 };
        int mid = -1;
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    @Test
    public void testDutchLargestMid() {
        int[] input = { 12, 34, 781, -1 };
        int mid = 781;
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    @Test
    public void testDutchWithoutMid() {
        int[] input = { 12, 34, 781, -1 };
        int mid = 90;
        FlagSorts.dutchFlag(input, mid);
        verifyDutch(input, mid);
    }

    private void verifyDutch(int[] input, int mid) {
        if (input == null || input.length < 2) {
            return;
        }
        for (int i = 1; i < input.length; i++) {
            if (input[i] < mid) {
                Assert.assertTrue(input[i - 1] < mid);
            } else if (input[i - 1] == mid) {
                Assert.assertTrue(input[i] >= mid);
            } else if (input[i - 1] > mid) {
                Assert.assertTrue(input[i] > mid);
            }
        }
    }

Update #1

The assert failure messages are wrong. Let me delete them until I write something more infomative

Maksim Dmitriev
  • 1.4k
  • 2
  • 15
  • 29