数组的插入问题
课堂上讲了,我也找了视频,但他们用的是最难的方法,看傻了啊【捂脸哭】
楼上的方法在输入一些数字重新排序之后,会出现问题,例如输入2
我找到了一种新的方式可供参考使用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSDNWenTi2
{
class Program
{
static void Main(string[] args)
{
int i;
int[] arr = new int[] { 1, 4, 6, 8, 9, 9, 11, 20 };
Console.WriteLine("请输入需要插入的数:");
int data = int.Parse(Console.ReadLine());
Insert(ref arr, data); //按引用传递
Console.WriteLine("重新排序的数组:");
for (i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
Console.ReadLine();
}
//在已排序数组arr中插入data,使之仍然有序
static void Insert(ref int[] arr, int data)
{
//data = int.Parse(Console.ReadLine());
int i;
Array.Resize<int>(ref arr, arr.Length + 1); //改变数组大小,使之长度增大1
//将比data大的元素后移
for (i = arr.Length - 2; i >= 0 && data < arr[i]; i--)
{
arr[i + 1] = arr[i];
}
arr[++i] = data; //插入data
}
}
}
int[] arr = { 1, 3, 5, 7, 9 }; //原有序数组
int x = int.Parse(Console.ReadLine()); //接收用户输入的X
int[] newArr = new int[arr.Length + 1]; //新数组大小加1
int insertIndex = 0; //插入新元素的索引
bool inserted = false; //是否已经插入新元素的标志
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > x && !inserted)
//找到第一个大于X的元素,将X插入到它前面
{
newArr[insertIndex] = x;
inserted = true;
}
else
{
newArr[insertIndex] = arr[i];
insertIndex++;
}
}
if (!inserted) //如果X比数组中所有元素都大,将X插入到末尾
{
newArr[newArr.Length - 1] = x;
}
foreach (int num in newArr)
{
Console.Write("{0} ", num); //输出新数组
}