Home » Java » Sorting algorithm which does not allow counting of elements

Sorting algorithm which does not allow counting of elements

Questions:

I have seen acrosss in a company interview test this question, but i am not clear about the question first. Could you people clarify my doubt ?

Question : Write a program to sort an integer array which contains Only 0’s,1’s and 2’s. Counting of elements not allowed, you are expected to do it in O(n) time complexity.

Ex Array : {2, 0, 1, 2, 1, 2, 1, 0, 2, 0}

• Remember the beginning of the list.
• Remember the position where the 1s start.
• Remember the end of the list.

Run through the whole array.

• If you encounter a 0, add it to the first position of the linked list.
• If you encounter a 1, add it after the position of the 1.
• If you encounter a 2, add it at the end of the list.

HTH

Raku

###

Instead of blasting you with yet another unintelligible pseudo-code, I’ll give you the name of the problem: this problem is known as the Dutch national flag problem (first proposed by Edsgar Dijkstra) and can be solved by a three-ways merge (see the PHP code in the first answer which solves this, albeit very inefficiently).

A more efficient in-place solution of the threeways merge is described in Bentley’s and McIlroy’s seminal paper Engineering a Sort Function. It uses four indices to delimit the ranges of the intermediate array, which has the unsorted values in the middle, the 1s at both edges, and the 0s and 2s in-between: After having established this invariant, the = parts (i.e. the 1s) are swapped back into the middle.

###

It depends what you mean by “no counting allowed”.

One simple way to do this would be to have a new empty array, then look for 0’s, appending them to the new array. Repeat for 1’s then 2’s and it’s sorted in O(n) time.

But this is more-or-less a radix sort. It’s like we’re counting the 0’s then 1’s then 2’s, so I’m not sure if this fits your criteria.

Edit: we could do this with only O(1) extra memory by keeping a pointer for our insertion point (starting at the start of the array), and scanning through the array for 0’s, swapping each 0 with the element where the pointer is, and incrementing the pointer. Then repeat for 1’s, 2’s and it’s still O(n).

Java implementation:

import java.util.Arrays;

public class Sort
{
public static void main(String[] args)
{
int[] array = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
sort(array);
System.out.println(Arrays.toString(array));
}

public static void sort(int[] array)
{
int pointer = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < array.length; j++)
{
if(array[j] == i)
{
int temp = array[pointer];
array[pointer] = array[j];
array[j] = temp;
pointer++;
}
}
}
}
}

Gives output:

[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]

###

Sorry, it’s php, but it seems O(n) and could be easily written in java 🙂

\$arr = array(2, 0, 1, 2, 1, 2, 1, 0, 2, 0);

\$tmp = array(array(),array(),array());
foreach(\$arr as \$i){
\$tmp[\$i][] = \$i;
}
print_r(array_merge(\$tmp,\$tmp,\$tmp));

###

In O(n), pseudo-code:

def sort (src):
# Create an empty array, and set pointer to its start.

def dest as array[sizeof src]
pto = 0

# For every possible value.

for val in 0, 1, 2:
# Check every position in the source.

for pfrom ranges from 0 to sizeof(src):
# And transfer if matching (includes update of dest pointer).
if src[pfrom] is val:
dest[pto] = val
pto = pto + 1

# Return the new array (or transfer it back to the source if desired).

return dest

This is basically iterating over the source list three times, adding the elements if they match the value desired on this pass. But it’s still O(n).

The equivalent Java code would be:

class Test {
public static int [] mySort (int [] src) {
int [] dest = new int[src.length];
int pto = 0;

for (int val = 0; val < 3; val++)
for (int pfrom = 0; pfrom < src.length; pfrom++)
if (src[pfrom] == val)
dest[pto++] = val;
return dest;
}

public static void main(String args[]) {
int [] arr1 = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
int [] arr2 = mySort (arr1);
for (int i = 0; i < arr2.length; i++)
System.out.println ("Array[" + i + "] = " + arr2[i]);
}
}

which outputs:

Array = 0
Array = 0
Array = 0
Array = 1
Array = 1
Array = 1
Array = 2
Array = 2
Array = 2
Array = 2

But seriously, if a potential employer gave me this question, I’d state straight out that I could answer the question if they wish, but that the correct answer is to just use Array.sort. Then if, and only if, there is a performance problem with that method and the specific data sets, you could investigate a faster way.

And that faster way would almost certainly involve counting, despite what the requirements were. You don’t hamstring your developers with arbitrary limitations. Requirements should specify what is required, not how.

If you answered this question to me in this way, I’d hire you on the spot.

###

This answer doesn’t count the elements.

Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up – making it match the typical java int loop.

public static void main(String[] args) throws Exception
{
Integer[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
List<Integer>[] elements = new ArrayList; // To store the different element types

// Initialize the array with new lists
for (int i = 0; i < elements.length; i++) elements[i] = new ArrayList<Integer>();

// Populate the lists
for (int i : array) elements[i].add(i);

for (int i = 0, start = 0; i < elements.length; start += elements[i++].size())
System.arraycopy(elements[i].toArray(), 0, array, start, elements[i].size());

System.out.println(Arrays.toString(array));
}

Output:

[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]

###

Push and Pull have a constant complexity!

1. Push each element into a priority queue

2. Pull each element to indices 0…n

(:

###

You can do it in one pass, placing each encountered element to it’s final position:

void sort012(int* array, int len) {
int* p0 = array;
int* p2 = array + len;
for (int* p = array; p <= p2; ) {
if (*p == 0) {
std::swap(*p, *p0);
p0++;
p++;
} else if (*p == 2) {
std::swap(*p, *p2);
p2--;
} else {
p++;
}
}
}

###

Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up – making it match the typical java int loop.

The whole sorting algorithm requires only three lines of code:

public static void main(String[] args)
{
int[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };

// Line 1: Define some space to hold the totals
int[] counts = new int; // To store the (3) different totals

// Line 2: Get the total of each type
for (int i : array) counts[i]++;

// Line 3: Write the appropriate number of each type consecutively back into the array:
for (int i = 0, start = 0; i < counts.length; start += counts[i++]) Arrays.fill(array, start, start + counts[i], i);

System.out.println(Arrays.toString(array));
}

Output:

[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]

At no time did we refer to array.length, no care how long the array was. It iterated through the array touching each element just once, making this algorithm O(n) as required.