whwqs的专栏

好好学习,天天向上

数据结构复习--数组的移动

删除数组中的0值,并使数组连续的两种算法比较:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace 线性表移动
{
    class Program
    {
        static void Main(string[] args)
        {
            new test().move1();
           
            new test().move2();
        }
        class test
        {// 删除0并向前移动

            int [] a;
            Stopwatch stopW = new Stopwatch();

            public test()
            {
                a =new int[]{0,1,2,0,1,0,9,0,0,9,2,3,4,5,6,0,2,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            }

            public void move1()
            {// 从前往后
                stopW.Reset();
                stopW.Start();
                int len = a.Length;
                for (int i = 0; i < len; i++)
                {
                    if (a[i] == 0)
                    {
                        for (int j = i+1; j < len; j++)
                        {
                            a[j - 1] = a[j];
                        }
                        len--;
                    }
                }
                stopW.Stop();
                Console.WriteLine(stopW.Elapsed);
            }

            public void move2()
            {// 从后往前
                stopW.Reset();
                stopW.Start();
                int len = a.Length;
                for (int i = len-1; i >=0; i--)
                {
                    if (a[i] == 0)
                    {
                        for (int j = i + 1; j < len; j++)
                        {
                            a[j - 1] = a[j];
                        }
                        len--;
                    }
                }
                stopW.Stop();
                Console.WriteLine(stopW.Elapsed);
            }
        }
    }
}

从后往前没有对0值的移动,所以要快很多.

阅读更多
个人分类: 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭