这是一个插入排序算法
我理解将最大的no转发到下一个索引,但是无法理解它何时向前移动它的先前位置(索引)是如何通过刚刚比较的较小数字来获取的,例如在列表中[2,1] 2移动到下一个索引按列表[j + 1] = list [j];但是1如何向后移动或向前一个索引
//unsorted array
int[] list = new int[] { 5, 2, 4, 6, 1 };
// the key element being sorted
int key;
//
//start looping starting from the second element
for (int i = 1; i < list.Length; i++)
{
key = list[i];//store the key
int j = i - 1;//get the previous index
//
//loop until you meet a smaller number or 0
while (j >= 0 && list[j] > key)
{
//move the greater number forward
list[j + 1] = list[j];
// Decrementing
j--;
}
//set the key in the proper index
list[j + 1] = key;
}
答案 0 :(得分:1)
这是在循环内的最后一行完成的。向前移动一个或多个(甚至零)物品后,当前值将被放置在正确的位置。
例如,如果您已将数组排序到最后一项,它看起来像这样:
2, 4, 5, 6, 1
将值1复制到key
变量中,然后逐项复制项目:
2, 4, 5, 6, - <- the empty slot here still contains 1, but it's unused
2, 4, 5, -, 6 <- the empty slot here still contains 6, but it's unused
2, 4, -, 5, 6
2, -, 4, 5, 6
-, 2, 4, 5, 6
现在key
变量的值放在最后一个项目的复制位置:
1, 2, 4, 5, 6
插入排序背后的理论是从一个数组中取出项目并插入到一个新数组中。您正在使用的实现仅使用单个数组,您可以将其视为分为已排序部分和未排序部分。已排序的部分以零大小开始:
[][ 5, 2, 4, 6, 1 ]
对数组进行排序时,将从未排序的部分中拾取项目,并将其插入已排序部分中的正确位置。已排序的部分会增长,未排序的部分会缩小,直到未排序的部分为空:
[ 5 ][ 2, 4, 6, 1 ]
[ 2, 5 ][ 4, 6, 1 ]
[ 2, 4, 5 ][ 6, 1 ]
[ 2, 4, 5, 6 ][ 1 ]
[ 1, 2, 4, 5, 6 ][]
答案 1 :(得分:0)
There are TWO lists/arrays
The declaration at the top...
int[] list = new int[] { 5, 2, 4, 6, 1 };
Says to make a list/array of integer format called X
X being whatever name you give it...
In this case the lists/arrays are list/array I[] and list/array J[]
So it (most likely) could be READING from one list/array maybe the I[] list/array
and assigning the SORTED values into the other list/array maybe the J[] list/array