-Java achieve Hill sorting

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/lixin88/article/details/91812666

Is a fast sort algorithm based on insertion sort; the other end of the scale for sorting disordered array insert is slow, as it can only switching the adjacent element, so the element only little by little to move from one end of the array . For example, if the smallest element in the right end of the primary key of the array, to be moved to its correct position requires N-1 or moved. Shell sort order to speed simply improved insertion sort, not adjacent switching elements to sort the local array, and finally with the partial insertion sort ordered array is sorted.

Array elements will now be sorted into a plurality of sub-sequences, such that the number of elements in each sub-sequence is relatively small, then the respective sequences direct insertion sort respectively, until the whole to be "substantially order" sort column, and finally to All the elements are a direct insertion sort.

Increments h, h is divided into groups, all the multiple of the distance h are in a group, the first group in the direct insertion sort,

Then take a second such repeat increments h2; increments until h = 1;

/**
 * 希尔排序
 * O(N*(logN)^2)
 */
public int[] shellSort(int[] a){
    if (a == null)
        return null;
    if (a.length ==1){
        return a;
    }

    int inserIndex = 0;
    int gap = a.length/2;
    while (gap>0)
    {
        for (int i = gap; i < a.length; i++) {
            inserIndex =i;
            int temp = a[i];
            while (inserIndex>=gap && a[inserIndex-gap]>temp){
                a[inserIndex] = a[inserIndex-gap];
                inserIndex-=gap;
            }
            a[inserIndex]=temp;
        }
        gap = gap/2;
    }
    return a;
}

 

 

Guess you like

Origin blog.csdn.net/lixin88/article/details/91812666