The Array Containing 3 Digits Only can also be sorted using any traditional sorting algorithm, but since we already know the array will contain 3 digits only, we can leverage this knowledge.
package org.wesome.dsalgo;
public class SortThreeDigitArray {
public static int[] sortThreeDigitArray(int[] array) {
int start = 0, end = array.length - 1, indx = 0, temp;
while (indx <= end) {
switch (array[indx]) {
case 0: {
temp = array[start];
array[start] = array[indx];
array[indx] = temp;
start++;
indx++;
break;
}
case 1: {
indx++;
break;
}
case 2: {
temp = array[indx];
array[indx] = array[end];
array[end] = temp;
end--;
break;
}
}
}
return array;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.wesome.dsalgo.java8.SortThreeDigitArray;
public class SortThreeDigitArrayTest {
@Test
void sortThreeDigitArrayTest1() {
int[] threeDigitArray = {0, 1, 2, 1, 0, 1, 2, 1, 2, 2, 0, 1};
Assertions.assertArrayEquals(new int[]{0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2}, SortThreeDigitArray.sortThreeDigitArray(threeDigitArray));
}
@Test
void sortThreeDigitArrayTest2() {
int[] binaryArray = new int[]{0, 0, 0, 1, 1, 1, 2, 2, 2};
Assertions.assertArrayEquals(new int[]{0, 0, 0, 1, 1, 1, 2, 2, 2}, SortThreeDigitArray.sortThreeDigitArray(binaryArray));
}
@Test
void sortThreeDigitArrayTest3() {
int[] binaryArray = new int[]{2, 2, 2, 1, 1, 1, 0, 0, 0};
Assertions.assertArrayEquals(new int[]{0, 0, 0, 1, 1, 1, 2, 2, 2}, SortThreeDigitArray.sortThreeDigitArray(binaryArray));
}
}
plugins {
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}