C# 插入排序

C# 插入排序,c#,algorithm,sorting,insertion-sort,C#,Algorithm,Sorting,Insertion Sort,我正在编写一个程序,使用插入排序对数字列表进行排序,但有一点我不明白 int[] a = { 5, 3, 8, 2, 1 }; for (int i = 0; i < 4; i++) { int key = a[i]; int j = i +1; int nextElement = a[j]; if (nextElement < key) {

我正在编写一个程序,使用插入排序对数字列表进行排序,但有一点我不明白

    int[] a = { 5, 3, 8, 2, 1 };

     for (int i = 0; i < 4; i++)
     {
         int key = a[i];
         int j = i +1;
         int nextElement = a[j];

             if (nextElement < key)
             {
                 swap(ref nextElement, ref key); 
             }
             else
             {

             }
     }
     for (int i =0;i<a.Length;i++)
     {
         Console.WriteLine("{0}", a[i]);
     }
 }

 static void swap(ref int x, ref int y)
 {
     int temp;
     temp = x;
     x = y;
     y = temp;
 }
int[]a={5,3,8,2,1};
对于(int i=0;i<4;i++)
{
int key=a[i];
int j=i+1;
int nextElement=a[j];
if(nextElement对于(int i=0;i而言,问题在于您正在交换
nextElement
key
,而不是
a[i]
a[j]
Int
是a,在您的情况下
nextElement
等于
a[i]
,但如果更改
nextElement
-
a[i]
值将不会更改

因此,您需要交换
a[i]
a[j]

if (a[i] > a[j]) {swap (ref a[i], ref a[j]); }
或者让swap函数将要交换的数组和索引作为参数

void swap (int a[], int i, int j) 
{
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}
然后你可以使用

if (a[i] > a[j]) {swap (a, i, j);}
包括
intmain()
{
int i=0,j=0,k=0,l=0,key=0;
INTA[20];
printf(“输入要排序的元素\n”);

对于(l=0;l不要发布代码截图。相反,复制代码并直接粘贴到帖子中。如果你想让人们真正响应,你应该更详细地描述你遇到的问题。具体问题是什么?不清楚你的代码在做什么或做得不正确。当然,如果我分配nextElement和key分别为a[i]和a[j],这无关紧要?@Ed_4434
int
是一种值类型,因此nextemet的值等于
a[i]
值,但如果更改
nextement
a[i]
不会更改。我明白了!非常感谢。@Ed_4434不客气。我强烈建议阅读/google了解值类型和引用类型之间的差异。
int main()
{
    int i=0,j=0,k=0,l=0,key=0;
    int a[20];

    printf("Enter the Elements to be sorted\n");
    for (l=0;l<=5;l++)
      {

          scanf("%d", &a[l]);
      }
    printf("the value of l is %d", l);
    printf("The Entered array elements are \n");
    for(k=0;k<l;k++)
      {
          printf("%d",a[k]);
      }


    for(j=1;j<l;j++)
      {
          key= a[j];
          i= j-1;
          while (i>=0 & a[i]>key)
               {
                    a[i+1] = a[i];
                    i=i-1;
               }

          a[i+1]=key;
      }
   printf("The Sorted array is \n");
   for (l=0;l<6;l++)
      {

          printf("%d", a[l]);
      }