views:

245

answers:

1

I have an array that I want to sort based on the value of one of the values in the array. The way I want to sort it is to evenly distribute the value I am searching for throughout the resulting array. For example -

Original array = [a,b,c,d,1,2,3,4]

I want to achieve - [a,1,b,2,c,3,d,4]

I can work out when to insert the numbers (total items / no. of numbers) = 2 so every 2nd item should be a number.

What is the easiest and most efficient way to do this type of sorting?

+3  A: 
var a = [a,b,c,d,1,2,3,4];
var half = a.length / 2;
var c = [];
for(var i = 0; i < half; i++)
{
  c.push(a[i]);
  c.push(a[half + i]);
}
a = c;

General solution:
Set r to appropriate value and make sure that array length corresponds to that value. For instance if r is 2, the ratio of number of letters to number of digits is 2:1 and hence the length of the array, len, should be a multiple of 3.

function mix(a:Array, r:Number):void
{
  var len1 = a.length * r / (r + 1);
  var len2 = a.length - len1;
  var c = [];
  for(var i = 0; i < len2; i++)
  {
    for(var j = 0; j < r; j++)
      c.push(a[i * r + j]);
    c.push(a[len1 + i]);
  }
  trace(c.join());
}
var r = 2; //two letters per one digit
//8 letters and 4 digits
var a = ['a','b','c','d','e','f','g','h','1','2','3','4'];
mix(a, r)   // a,b,1,c,d,2,e,f,3,g,h,4

r = 3; //three letters per one digit
//9 letters and 3 digits
a = ['a','b','c','d','e','f','g','h','i','1','2','3'];
mix(a, r);  // a,b,c,1,d,e,f,2,g,h,i,3
Amarghosh
Thanks, but what if its not half and half, for example if I have an array - [a,b,c,d,e,f,1,2] and I want [a,b,1,c,d,2,e,f]
undefined
@undefined see my update
Amarghosh
Great, thanks Amarghosh.
undefined