views:

51

answers:

4

Just for fun really. I was curious of the best way to do this.

+1  A: 

I would do the following:

  1. Sort the original array by length of the strings (with uasort())
  2. Split the array in half by putting every element in one of two arrays (in a foreach loop)
  3. Reverse the second array (with array_reverse())
  4. Merge the two array together (with array_merge())
Kau-Boy
No need to re-sort the second half as it’s already sorted. You just have to reverse the order.
Gumbo
That's why I used the array_reverse function :) Ok I'll change my sentence.
Kau-Boy
You will always have a right-heavy array but I believe this still passes the spec.
erisco
+3  A: 

Here is one way to do it (there's most likely a better solution):

function sort_length($str1, $str2)
{
    if(strlen($str1) == strlen($str2))
    {
        return 0;
    }
    return strlen($str1) > strlen($str2) ? -1 : 1;
}
$words = array("Hello", "World", "this", "is", "a", "test");
usort($words, 'sort_length');

$new_list = array();
$boolean = true;
foreach($words as $word)
{
    if($boolean)
    {
        array_push($new_list, $word);
    }
    else
    {
        array_unshift($new_list, $word);
    }
    $boolean = !$boolean;
}

//print_r($new_list);
Tim Cooper
A: 

A first attempt could be to first sort them as normal. Then iterate through this array, copying to a new one, with the copy destination alternating between the start and end of the new array, where the start index is incremented and the end index is decremented.

James
+1  A: 

Here’s a solution that preserves the array keys:

// function to compare two strings by their length
function cmp_strlen($a, $b) {
    return strlen($a) - strlen($b);
}

// sort array by length while preserving the keys
uasort($arr, 'cmp_strlen');

$ordered = array();
$keys = array_keys($arr);

// fill $ordered with odd keys in order
for ($i=0, $n=count($keys); $i<$n; $i+=2) {
    $ordered[$keys[$i]] = $arr[$keys[$i]];
}
// fill $ordered with even keys in reverse order
for ($i=((count($keys)>>1)<<1)-1; $i>0; $i-=2) {
    $ordered[$keys[$i]] = $arr[$keys[$i]];
}
Gumbo