首页 > 代码库 > 递归算法和栈运行效率的比较
递归算法和栈运行效率的比较
以下是时间对比,第二张图是使用得递归算法,第一张图使用的栈,使用栈来实现还是要快那么一点。使用递归的程序请参考我昨天的博客。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
List<string> allFileName = new List<string>();
string[] drives = Directory.GetLogicalDrives();
Stack<string> stack = new Stack<string>();
foreach (string drive in drives)
{
stack.Push(drive);
}
string path;
DirectoryInfo sDir;
FileInfo[] fileArray;
DirectoryInfo[] subDirArray;
while (stack.Count > 0)
{
path = stack.Pop();
sDir = new DirectoryInfo(path);
try
{
fileArray = sDir.GetFiles();
foreach (FileInfo file in fileArray)
{
allFileName.Add(file.FullName);
}
}
catch (Exception e)
{
}
try
{
subDirArray = sDir.GetDirectories();
foreach (DirectoryInfo subDir in subDirArray)
{
stack.Push(subDir.FullName);
}
}
catch (Exception e)
{
}
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.WriteLine(allFileName.Count);
Console.ReadLine();
}
}
}
递归算法和栈运行效率的比较