从多个预排序数组创建排序数组 [英] Create sorted array from multiple pre-sorted arrays

查看:109
本文介绍了从多个预排序数组创建排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从可变数量的预排序数组中创建一个排序数组.

I would like to create a sorted array from a variable number of pre-sorted arrays.

给出{A1, ..., An}是预先排序的数组,我想创建At,它是{A1, ..., An}的组合,并且以相同的方式排序.

Given {A1, ..., An} which are pre-sorted arrays, I would like to create At, which is the combination of {A1, ..., An} and is sorted in the same way.

示例:

Given :
A1 = [2, 4, 9, 16]
A2 = [-3, 4, 98, 116]
...
An = [1, 7, 17, 76, 512]

I would like :
At = [-3, 1, 2, 4, 4, 9, 16, 17, 76, 98, 116, 512] 

计算此数组的最有效方法是什么?

What it is the most efficient way to compute this array ?

谢谢

推荐答案

我已经实现了所需的功能.

I have implemented a function doing what I want.

您如何看待演出?您对它有什么建议吗?

What do you think of the performance ? Do you have any advice to improve it ?

排序功能:

function sortPreSortedArrays($arrays, $comparisonFunction, $order = 'asc')
{
    $sortedArray = array();

    /* Sort */

    while(sizeof($arrays) !== 0)
    {
        /* Find the greatest value */

        $max = true;
        $keyMax = -1;

        foreach($arrays as $key => $array)
        {
            if($max === true || $comparisonFunction(end($array), $max))
            {
                $max = end($array);
                $keyMax = $key;
            }
        }

        /* Take the greatest value */

        array_push($sortedArray, array_pop($arrays[$keyMax]));
        if(sizeof($arrays[$keyMax]) === 0) unset($arrays[$keyMax]);
    }

    /* Return */

    if($order === 'asc')
        return array_reverse($sortedArray);
    else
        return $sortedArray;

比较功能:

function compareLogArrayDate($log1, $log2)
{
    $t1 = $log1['date'];
    $t2 = $log2['date'];

    return ($t1 > $t2) ? true : false;
}

为了提高性能,我尝试使用最有效的数组函数(array_pop O(1)代替array_shit O(n).尽管如此,我仍在使用unset.:|

In order to improved the performancse, I have tried do use the most efficient array functions (array_pop O(1) instead of array_shit O(n). Nevertheless I am still using unset. :|

这篇关于从多个预排序数组创建排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆