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

来源:互联网 发布:淘宝手机端主页尺寸 编辑:程序博客网 时间:2024/05/22 07:40

删除数组中的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值的移动,所以要快很多.

原创粉丝点击