码迷,mamicode.com
首页 > 编程语言 > 详细

递归算法和栈运行效率的比较

时间:2014-10-29 13:16:17      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:http   io   os   ar   使用   for   sp   on   2014   

以下是时间对比,第二张图是使用得递归算法,第一张图使用的栈,使用栈来实现还是要快那么一点。使用递归的程序请参考我昨天的博客。

bubuko.com,布布扣bubuko.com,布布扣


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

递归算法和栈运行效率的比较

标签:http   io   os   ar   使用   for   sp   on   2014   

原文地址:http://my.oschina.net/u/855028/blog/338370

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!