我正在编写一个程序来使用插入排序来命令一个数字列表,这是我不理解的东西。
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;
}
这是我到目前为止所写的内容,但我实际上无法理解如何实现该算法。它只是查看前面的元素并将元素排序到它们中吗?
答案 0 :(得分:2)
问题是您正在交换nextElement
和key
而不是a[i]
和a[j]
。
Int
是value type,在您的情况下nextElement
等于a[i]
,但如果您更改nextElement
- a[i]
值则赢了改变了。
因此您需要交换a[i]
和a[j]
。
if (a[i] > a[j]) {swap (ref a[i], ref a[j]); }
或者只是使交换函数将数组和索引作为参数交换
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);}
答案 1 :(得分:0)
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]);
}
}