《C#数据结构与算法》–2020 最新精讲版 2-5 动态数组 #笔记
学习视频以及前言回顾
《C#数据结构与算法》–2020 最新精讲版_2-4 包含、搜索、删除 笔记
《C#数据结构与算法》–2020 最新精讲版 2-5 动态数组 视频
一、扩容和缩容
前面几节课的学习已经实现增 删 改 查四个基本功能,但是任然存在两个局限性。
无法实现扩容和缩容的功能
在我们实现的数组类中底层是用静态数组data进行数据的存储,它的容量是有限的,很多时候我们无法预估所需存储的元素个数。容量开的太大就会浪费过度的空间,容量开的太小空间又不够用。————动态数组就能很好的解决这一问题。
// 重新开辟一个内容空间
private void ResetCapacity(int newCapacity)
{
int[] newData = new int[newCapacity];//新建一个数组,大小是形参
for (int i = 0; i < N; i++)
newData[i] = data[i];//将之前的数组数据都赋值给新的数组
data = newData;//将新创建的数组赋值给全局变量data,这样就实现了数组data的扩容。
}
在添加中修改:容量不够就扩容两倍
public void Add(int index, int e)
{
if (index < 0 || index > N)
{
throw new ArgumentException("数组索引越界");
}
//如果长度不够则扩容两倍
if (N == data.Length)
{
ResetCapacity(2*data.Length);
}
for (int i = N - 1; i >= index; i--)
data[i + 1] = data[i];
data[index] = e;
N++;
}
在删除中修改:容量多出一半,则缩容
// 将后面的元素向前移动并覆盖前一位
public int RemoveAt(int index)
{
if (index < 0 || index >= N)
throw new ArgumentException("数组索引越界");
int del = data[index];
for (int i = index + 1; i <= N - 1; i++)
data[i - 1] = data[i];
N--;
data[N] = default(int);
if (N == data.Length / 2)
ResetCapacity(data.Length/2);
return del;
}
二、测试
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace array
{
class Program
{
static void Main(string[] args)
{
Array1 a = new Array1(10);
for(int i=0;i<10;i++)
{
a.AddLast(i);
}
Console.WriteLine(a);
Console.ReadKey();
a.AddLast(55);;
Console.WriteLine(a);
Console.ReadKey();
for(int i=0;i<6;i++)
{
a.RemoveAt(i);
Console.WriteLine(a);
}
Console.ReadKey();
}
}
}
//测试结果如下
Array1:count=10 capacity=10
[0,1,2,3,4,5,6,7,8,9]
Array1:count=11 capacity=20
[0,1,2,3,4,5,6,7,8,9,55]
Array1:count=10 capacity=10
[1,2,3,4,5,6,7,8,9,55]
Array1:count=9 capacity=10
[1,3,4,5,6,7,8,9,55]
Array1:count=8 capacity=10
[1,3,5,6,7,8,9,55]
Array1:count=7 capacity=10
[1,3,5,7,8,9,55]
Array1:count=6 capacity=10
[1,3,5,7,9,55]
Array1:count=5 capacity=5
[1,3,5,7,9]