java算法(一)——排序算法(下)之 插入排序

插入排序算法通过比较和插入来进行排序,其流程如下:
(1)首先对数组的前两个数据进行从大到小排列
(2)接着将第3个数据与排好的前两个数据进行比较,将第3个数据插入合适的位置。
(3)然后,将第4个数据插入已排序的前3个数据中。
(4)不断重复上述过程。

static void  insertionSort(int a[]){
        int i,j,t,h;

        for(i = 1;i<a.length;i++)
        {
            t = a[i];
            j = i-1;
            while(j >= 0 && t<a[j])
            {
                a[j+1] = a[j];
                j--;
            }
            a[j+1] = t;
        }
        for(h = 0; h<a.length; h++)
        {
            System.out.print(" "+a[h]);
        }
        System.out.print("\n");

    }

插入排序是之前的shell排序的基础。

猜你喜欢

转载自blog.csdn.net/h9f3d3/article/details/52206236