java数据结构之插入排序
static int[] insertion_sort(int[] unsorted)
{
//默认从第二个开始,默认第一个是有序的
for (int i = 1; i < unsorted.length; i++)
{
//如果后来的元素的小于前面的元素
if (unsorted[i - 1] > unsorted[i])
{
//设置临时变量记录后来的元素
int temp = unsorted[i];
//记录后来元素的位置
int j = i;
//后来的元素依次跟前面的元素进行比较
while (j > 0 && unsorted[j - 1] > temp)
{
//如果后来的元素小于当前比较元素,依次移动数组中的元素
unsorted[j] = unsorted[j - 1];
j--;
}
//将后来元素插入到正确的位置
unsorted[j] = temp;
}
}
return unsorted;
}
浙公网安备 33010602011771号