search

Home  >  Q&A  >  body text

c++ - 请问C#中如何写出插入数据算法?

请问C#中如何写出插入数据算法? 不需要排序,只要在数组中插入数据,并使所有后续数值后移。这种算法该怎么写?

巴扎黑巴扎黑2807 days ago584

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:06:34

    Then don’t use arrays, use linked list structures. Classes have objects of their own type that point to the next and previous ones. Search for linked list algorithms. There are many C# versions.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:06:34

    https://msdn.microsoft.com/en-us/library/he2s3bh7(v=vs.110).aspx

    The questioner thinks too much, the linked list class is already available in .net.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:06:34

    The array size is immutable

    public int[] InserFunction(int[] inarr, int data, int position)
    {
        int[] outarr = new int[inarr.Length + 1];
        outarr[inarr.Length] = data;
        for (int ini = 0; ini < inarr.Length; ++ini) outarr[ini] = inarr[ini];
        for (int i = inarr.Length; i > position; --i)
        {
            int ex = outarr[i];
            outarr[i] = outarr[i - 1];
            outarr[i - 1] = ex;
        }
        return outarr;
    }

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:06:34

    With LinkedList, there is an AddFirst() method that can be added to the head of the list.

    reply
    0
  • Cancelreply