数据结构(四十四)插入排序(1.直接插入排序 2.希尔排序)

  一、直接插入排序的定义

  直接插入排序就是将一个记录插入到已经排好序的有序表中,从而得到一个新的、记录数增1的有序表。

  

  二、直接插入排序的实现

    public static void straightInsertionSort(int[] L) {
        int i, j, temp;
        for (i = 0; i < L.length - 1; i++) {    
            temp = L[i+1];                        // 保存要插入的数据元素
            j = i;                                
            while (j > -1 && temp <= L[j]) {    // 将temp插入到原数组集合中
                L[j+1] = L[j];
                j--;
            }
            L[j+1] = temp;                         
        }
    }

  int[] array1 = {9,1,5,8,3,7,4,6,2};
  初始时,子集合中L0已经排好序,即为{9}
  i=0时,temp=L1=1,j=0,0大于-1且1小于9,则L1=9,j=-1,L0=1,即将1插入到9的前面,集合中{1,9}
  i=1时,temp=L2=5,j=1,1大于-1且5小于9,则L2=9,j=0,0大于-1但5不小于1,则L1=5,集合中{1,5,9}
  i=2时,temp=L3=8,即将8和9比较,8插入到9的前面,8和5比较,不动,8和1比较,也不动,集合中{1,5,8,9}
  ...

  三、直接插入排序的

  

猜你喜欢

转载自www.cnblogs.com/BigJunOba/p/9298172.html