算法---插入排序

58 阅读1分钟

规则

  • 将0索引的元素到N索引看作是有序的(从小到大),把N+1到数组最后一个看作是无序的
  • 遍历无序的数据,将遍历的元素插入到有序序列中适当的位置,如遇到相同的插到后面
  • N的范围:0~最大索引

案例

int[] array = {2, 40, 38, 5, 50, 30, 3, 10, 2};

//假设无序的从-1开始
int unorderedIndex = -1;

for (int i = 0; i < array.length; i++) {
    if (array[i] > array[i + 1]) {
        //获取无序的开始下标
        unorderedIndex = i + 1;
        //获取到直接跳出循环
        break;
    }
}
//打印无序数据的开始索引
System.out.println(unorderedIndex);

//从unorderedIndex 遍历到数组最后
for (int i = unorderedIndex; i < array.length; i++) {

    //记录当前要插入数据的索引值
    int j = i;
    while (j > 0 && array[j] < array[j - 1]) {
        //交换位置
        int temp = array[j];
        array[j] = array[j - 1];
        array[j - 1] = temp;
        j--;
    }
}

//遍历数组查看结果
for (int j : array) {
    System.out.print(j + " ");// 2 2 3 5 10 30 38 40 50 
}