Pre-content: [JAVA] Direct insertion sort_HY_PIGIE's Blog-CSDN Blog
Hill sorting is to divide an array into multiple groups and sort within each group. Every time a sort is performed, the elements in the group will increase and the number of groups will decrease.
Insertion sort directly within a group
The number of groups is reduced by /2
For example, an array contains 6 elements. Initially, two elements can be used as a group, and the number of groups gap is: 8/2=4 groups.
direct insertion sort in each group
The number of elements in the group is increased, and the number of groups sorted for the second time can be gap: 4/2=2;
Sorting process:
Pay attention to the observation that the sorting in the group is carried out alternately, instead of arranging the elements in a whole group in an orderly manner at one time.
After sorting:
The third sorting, the number of groups gap: 2/2=1
We can find that after each sorting, the array as a whole gradually tends to be in order. At this time, the entire array is used as a group to perform overall sorting.
After sorting it is:
On the code!
import java.util.Arrays;
public class Test {
public static void shell(int[] array,int gap){
//可以思考一下为什么i从gap开始呢?
//i从gap开始,表示的就是第一组的第二个元素
//gap其实是每一组相邻元素在整体数组内下标的联系
//gap是两个相邻元素的下标的差额
//每个组内进行插入排序
for(int i = gap; i < array.length; i++){
//i表示每一组的开头
//i++表示的是每一组的排序交替进行
//即A组进行一次插入排序后,B组进行一次,然后A在进行一次,循环往复
int j = i - gap;
int tmp = array[i];
for(; j >= 0; j -= gap){
if(tmp < array[j]){
array[j+gap] = array[j];
}else{
break;
}
}
array[j+gap] = tmp;
}
}
public static void shellSort(int[] array){
int gap = array.length;
while(gap > 1){
//最后一次排序是整个数组为一组的时候
gap /= 2;//组数每一次都/2
shell(array,gap);
}
}
public static void main(String[] args) {
int[] array = {12,89,2,4,61,50};
shellSort(array);
System.out.println(Arrays.toString(array));
}
}