Dutch national flag problem is a classic programming problem. It groups the input array into three sub-groups in just one pass. For detailed information, please refer to http://en.wikipedia.org/wiki/Dutch_national_flag_problem

function x = category_sort(x, low, high)
len = length(x);
p = 1; q = len;
i = 1;
while i <= q
if x(i) < low % move the current element to the front
tmp = x(p);
x(p) = x(i);
x(i) = tmp;
p = p + 1;
i = i + 1;
elseif x(i) >= high % move the current element to the back
tmp = x(q);
x(q) = x(i);
x(i) = tmp;
q = q - 1;
else % move to the next element in the array
i = i + 1;
end
end

We can test the code by simply running the following script:

x = 3 * rand(20, 1);
x = category_sort(x, 1, 2)