开发者

Best way to sort an array with the longest strings in the middle and the shortest at the beginning and end

开发者 https://www.devze.com 2023-01-15 10:36 出处:网络
Just f开发者_JS百科or fun really. I was curious of the best way to do this. Here is one way to do it (there\'s most likely a better solution):

Just f开发者_JS百科or fun really. I was curious of the best way to do this.


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);


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())


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]];
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消