【排序】插入排序

直接插入排序(Insertion Sort)的基本思想是:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子序列中的适当位置,直到全部记录插入完成为止。

 

设数组为a[0…n-1]。

1.      初始时,a[0]自成1个有序区,无序区为a[1..n-1]。令i=1

2.      将a[i]并入当前的有序区a[0…i-1]中形成a[0…i]的有序区间。

3.      i++并重复第二步直到i==n-1。排序完成。

 

不断扩大有序区的过程

package sort;

public class insertSort {
    public static void main(String[] args) {
        int[] a = new int[] {2,15,42,4,8,9,46,17};
        insertsort(a,8);
        for(Integer i : a)
            System.out.println(i);    
    }
    static void insertsort(int[] a, int n) {
        for(int i = 1; i < n; i++) {
            int temp = a[i];
            int j = i-1;
            for(; j >= 0; j--) {
                if(a[j] <= temp) break;
                a[j+1] = a[j];
            }
       // j = -1 或者 a[j] <= temp时候退出 a[j
+1] = temp; } } } /**改进版
static void insertsort(int[] a, int n) {   for(int i = 1; i < n; i++) {   for(int j = i-1; j>=0&& a[j]>a[j+1]; j--){   //交换a[j]和a[j+1]   int temp = a[j];   a[j] = a[j+1];   a[j+1] = temp;    }   } }
*/
原文地址:https://www.cnblogs.com/chengdabelief/p/7479371.html