• 外层循环从索引`1`开始，遍历整个数组（第7行）
• 将外层循环当前元素储存在临时变量里（第9行）
• 设置目标位置索引为外层循环的当前索引（第10行）
• 内层循环从外层循环的当前位置往数组开头进行，将元素右移直到待移动元素比临时变量小为止（第11-15行）
• 内层循环结束后，将临时变量的内容替换到空出的正确位置（第16行）

```import java.util.Arrays;

public class SortTest
{
public static void insertionSort(int[] elements)
{
for (int j = 1; j < elements.length; j++)
{
int temp = elements[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp < elements[possibleIndex - 1])
{
elements[possibleIndex] = elements[possibleIndex - 1];
possibleIndex--;
}
elements[possibleIndex] = temp;
}
}

public static void main(String[] args)
{
int[] arr1 = {3, 86, -20, 14, 40};
System.out.println(Arrays.toString(arr1));
insertionSort(arr1);
System.out.println(Arrays.toString(arr1));
}
}```

0:00

Under what condition will an insertion sort execute faster?

1

This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong?

```public static void insertionSort(int[] elements)
{
for (int j = 1; j < elements.length - 1; j++)                       // line 1
{
int temp = elements[j];                                          // line 2
int possibleIndex = j;                                           // line 3
while (possibleIndex > 0 && temp < elements[possibleIndex - 1])  // line 4
{
elements[possibleIndex] = elements[possibleIndex - 1];        // line 5
possibleIndex--;
}
elements[possibleIndex] = temp;
}
}```

1