如何计算 C# 中的时间复杂度 [关闭]

问题描述 投票:0回答:1

尝试解决算法问题https://www.w3resource.com/csharp-exercises/basic-algo/index.php 7. 我用这个代码解决了问题

class Program
{
    static void Main(string[] args)
    {
        Algorithms algorithms = new Algorithms();
        algorithms.StringReverse("abcd");
    }
}


class Algorithms
{
    public void StringReverse(string items)
    {
        char[] Items = items.ToCharArray();
        char NewElements = Items[0];

        Items[0] = Items[Items.Length - 1];
        Items[Items.Length - 1] = NewElements;

        Console.WriteLine(Items);
    }
}

如何计算这段代码的时间复杂度

(我怎么知道它是不是一个好的算法?)

c# algorithm profiling
1个回答
0
投票

有几种工具可以分析代码,但是在您学习的过程中,我建议您简单地使用

StopWatcher
(天文钟)

static void Main(string[] args)
{
    Algorithms algorithms = new Algorithms();
    Stopwatch mytimer = new Stopwatch();
    mytimer.Start();
    algorithms.StringReverse("abcd");
    mytimer.Stop();
    Console.WriteLine("Time elapsed: " +  mytimer.Elapsed.ToString(@"d'd, 'hh\:mm\:ss\.fff");
}
© www.soinside.com 2019 - 2024. All rights reserved.