Skip to content
Advertisement

How to sort array based on multiples of 3 using Java

I have an array like this one-

{1, 2, 3, 4, 5, 6}

I want to sort it in the order of multiples of 3 with remainders 0, 1 and 2. (the first group is multiples of 3, the second one is multiples of 3 with remainder 1 and the last one is multiples of 3 with remainder 2) and I want to preserve the order in which elements appear in the array. The result should be – {3, 6, 1, 4, 2, 5}

I have this code-

int current = 0;
int b = 0;
for (int i = 0; i < 3; i++) { //3 groups
    for (int j = current; j < numbers.length; j++) {
        if (numbers[j] % 3 == i) { //reminder should be 0,1 or 2
            b = numbers[j];
            numbers[j] = numbers[current];
            numbers[current] = b;
            current++;
        }
    }
}

But this code does not preserve the order in which elements appear in the array. The result I got is-

{3, 6, 1, 4, 5, 2}

But I want the result to be like {3, 6, 1, 4, 2, 5}. How can I achieve this?

Advertisement

Answer

Using stream and comparator

int[] array = {1, 2, 3, 4, 5, 6};
List<Integer> lst = Arrays.stream(array)
  .boxed()
  .sorted(Comparator.comparingInt(o -> o % 3))
  .collect(Collectors.toList());

System.out.println(lst);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement