Counting sort
if you have only blue and red
you counting blue elements and red elements
[b1 r1 r2 b2 b3 r3 r4 b4 r5]
and in for loop you count yours elements
you have blue: 4 red: 5
then you knew result table is [ r r r r r b b b b]
and you can know index range where is reds elements and blue elements (last red element is {red_count}-1 and last blue element is {red_count}+{blue_count}-1 ) you save this values to redIndex and blueIndex
you make second table and in for loop from end you search elements, the last is r5 its red then his index should be 4 and you decrement redIndex
[b1 r1 r2 b2 b3 r3 r4 b4 __] blueIndex:8
[__ __ __ __ r5 __ __ __ __] redIndex:3
[b1 r1 r2 b2 b3 r3 r4 __ __] blueIndex:7
[__ __ __ __ r5 __ __ __ b4] redIndex:3
[b1 r1 r2 b2 b3 r3 __ __ __] blueIndex:7
[__ __ __ r4 r5 __ __ __ b4] redIndex:2
.....
The faster way to sort items O(2n) but with huge memory usage when various data
aarray holds only card colours why won't you just count them and then recreate the array by filling it with appropriate values?