Author:hiyo585
/*
* Author:hiyo585
* Company:hiyo studios
* 数组的应用
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayDemo
{
internal class Program
{
//向数组中添加元素
static int[] AddArray(int[] ArrayBorn,int Index, int Value)
{
if(Index >= ArrayBorn.Length)
{
//判断添加索引是否大于数组的长度
//如何添加的索引大于数组的长度,则将索引设置为数组的最大索引。
Index = ArrayBorn.Length - 1;
}
//声明一个新的数组
int[] TemArray = new int[ArrayBorn.Length+1];
for(int i=0 ; i < TemArray.Length; i++)
{
//判断索引是否大于或等于0
if(Index >= 0)
{
if (i < (Index + 1)) //判断遍历的索引是否小于添加索引+1
TemArray[i] = ArrayBorn[i];
else if (i == (Index + 1)) //判断遍历的索引是否等于添加索引+1
TemArray[i] = Value; //要添加的数组元素值
else
TemArray[i] = ArrayBorn[i - 1];//因为中间添加了一个元素,所以是i-1;
}
else //就是Index < 0
{
if (i == 0) //判断遍历的索引是否为0
TemArray[i] = Value; //在最开始的位置插入元素
else //就是i!=0,后面的元素怎么存入新的数组中
TemArray[i] = ArrayBorn[i-1];
//即TemArray[i]的第i个元素是ArrayBorn中的i-1个元素,因为开头插入了一个元素。
}
}
return TemArray;
}
//原来数组添加一个数组
static int[] AddAllArray(int[] ArrayBorn, int[] ArrayAdd, int Index)
{
//判断index的位置
if(Index >=(ArrayBorn.Length))
Index = ArrayBorn.Length - 1; //如果Index的值超过了原始数组的值,赋值为最大值
int[] TemArray = new int[ArrayBorn.Length + ArrayAdd.Length];//创建能容纳两个数组的大数组
//遍历数组中的元素
for(int i=0 ;i < TemArray.Length; i++) //大数组作为遍历条件
{
if (Index >= 0)//插入位置为0和正
{
if (i < (Index + 1))
TemArray[i] = ArrayBorn[i]; //遍历索引值在之前的直接复制原始数组
else if (i == (Index + 1)) //遍历索引值在插入的位置
{
for (int j = 0; j < ArrayAdd.Length; j++)
TemArray[i + j] = ArrayAdd[j]; //将需要加入的新数组加入到原数组后面
i = i + ArrayAdd.Length - 1; //同时索引值也在变化
}
else //索引大于插入位置,将后面的数组元素拷贝到大数组
TemArray[i] = ArrayBorn[i - ArrayAdd.Length];
}
else
{
if(i==0)
{
for(int j=0; j < ArrayAdd.Length; j++)
TemArray[i+j] = ArrayAdd[j];
i = i + ArrayAdd.Length - 1;
}
else
TemArray[i] = ArrayBorn[i-ArrayAdd.Length];
}
}
return TemArray;
}
static void Main(string[] args)
{
//遍历数组
int[] arr = new int[10]{10,20,30,40,50,60,70,80,90,100};
//foreach遍历数组
Console.WriteLine("原始数组:");
foreach(int i in arr)
{
Console.Write(i + " ");
}
Console.WriteLine();
//向数组中添加元素
arr = AddArray(arr, 4, 200);
Console.WriteLine("插入元素之后的 数组:");
foreach(int j in arr)
{
Console.Write(j + " ");
}
Console.WriteLine();
int[] ArrayInt1 = new int[] {0,1,2,4,9,10 };
int[] ArrayInt2 = new int[] { 10, 20, 30, 40, 50, 60 };
int[] FinalArray = AddAllArray(ArrayInt1, ArrayInt2, -2);
foreach (int x in FinalArray)
Console.Write(x + " ");
Console.ReadLine();
}
}
}