Algorithm - Hill Sort

package com.arithmetic.sort;
/**
 * Shell Sort is actually an optimization of Insert Sort, because when an initialized array is ordered or relatively ordered, and the amount of data
 * When it is not too big, it may not be a big problem. When the initialized array is large and disorganized, when inserting sorting, the number of insertions is very large.
 * This also greatly reduces the efficiency. So at this time Shell Sort can be a set of arrays that are close to ordered, and then inserted into sorting, in this case
 * The number of insertions is very small
 * @author Administrator
 *
 */
public class ShellSort {
	public static void main(String[] args) {
		int [] arrays = new int[]{1002,2,989,344,24,3,15,6,909,13,12,112,56,100,67,81,671,456,23,231,34,456,567,98,123};
		//calculate the length of the array
		int len = arrays.length;
		//Control how much the increment changes, depending on the actual situation, here we assume that the increment is 5, and each time decreases by 2, but make sure that the increment is greater than 0 at the end
		for(int gap = 5; gap > 0; gap -= 2){
			//We need to start from 0 and traverse the data, but the length of the length variable is best not to exceed (len-gap) because it exceeds the group that was convenient before.
			for(int x = 0; x < len-gap; x++){
				//At this point, we need to get all the data of the group according to the first data of each group
				for(int y = x; y < len; y += gap){
					//start insertion sort
					for(int index = y; index > 0; index-=gap){
						//If the subscript of the starting position is less than the increment, we skip this loop, otherwise the subscript of the array is out of bounds
						if(index < gap){
							continue;
						}
						if(arrays[index] < arrays[index-gap]){
							int tmp = arrays[index];
							arrays[index] = arrays[index-gap];
							arrays[index-gap]= tmp;
						}
					}
				}
			}
		}
		for(int i = 0; i<arrays.length;i++){
			System.out.print(arrays[i]+" ");
		}
		System.out.println();
	}
	
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327062293&siteId=291194637