Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can\'t be rearranged it can be put
In javascript, I'd probably do:
var arr = [ 1, 1, 1, 2, 3 ];
var i = 0, len = arr.length;
while (i < len - 1) {
if (arr[i] == arr[i+1]) {
//index is equal to it's partner.
if (arr[i+2] && arr[i] == arr[i+2]) {
// 3 equal values in a row, swapping won't help. Need to recheck this index in this case.
var tmp = arr[i];
arr.splice( i, 1 );
arr.push( tmp );
} else {
// Swap the next and 2nd next index.
var tmp = arr[i+1];
arr[i+1] = arr[i+2];
arr[i+2] = tmp;
i++;
}
} else {
// this index is fine, move on.
i++;
}
}
This is a quick example, coding style could probably be cleaned up a lot
Assuming A Array Containing Digits Between 0 To 9:
Similar To Bucket Sort In A Way
int B[10];//buckets
diff=0;//how many different digits appeared
for(i=0;i<A.length;i++)
{
x=A[i];
if(B[x]==0)
{
diff++;
}
B[x]++;
}//loaded
while(diff>=0)//now to place back to array makes an interleaving
{
for(digit=0;digit<10;digit++)
{
if(B[digit]<>0)
{
A[B[digit]+diff]=digit;
B[digit]--;
}
}
diff--;
}