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

本文对比了两种删除数组中零值并保持数组连续性的算法:一种是从数组头部开始处理,另一种是从尾部开始处理。实验结果显示,从数组尾部开始处理的方法效率更高。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值