2.4.37

2.4.37 #

解答 #

建立一个全局变量 isRunning ,每次 DelMax() 之前都先确认这个值是否为 true

设立一个 Timer 在 1 秒钟之后自动将 isRunning 置为 false

测试结果如下:

随着 n 增大,一秒钟之内能执行的 DelMax() 次数会下降。

代码 #

var doubleTime = 6;
var repeatTime = 6;
var n = 1000000;
var isRunning = true;
for (var i = 0; i < doubleTime; i++)
{
    var totalDelCount = 0;
    Console.WriteLine("count=" + n);
    for (var j = 0; j < repeatTime; j++)
    {
        var pq = new MaxPq<int>(n);
        var delCount = Test(n, pq);
        totalDelCount += delCount;
        Console.Write(delCount + "\t");
    }

    Console.WriteLine("平均最大删除次数:" + totalDelCount / repeatTime);
    n *= 2;
}


int Test(int count, MaxPq<int> pq)
{
    var random = new Random();
    var timer = new Timer(1000);
    timer.Elapsed += StopRunning;
    for (var i = 0; i < count; i++)
    {
        pq.Insert(random.Next());
    }

    var delCount = 0;
    StartRunning();
    timer.Start();
    while (isRunning && !pq.IsEmpty())
    {
        pq.DelMax();
        delCount++;
    }

    timer.Stop();
    return delCount;
}

void StartRunning() => isRunning = true;
void StopRunning(object source, ElapsedEventArgs e) => isRunning = false;

另请参阅 #

PriorityQueue 库