Hill sorting of advanced sorting

1. The simple sorting mentioned above is continuous (meaning that each element is compared with other elements one by one), while the sorting of Hasher is jumping (relying on a preset increment. Quantity), based on this, the interval between an element and other elements is h, and then h is gradually reduced, and it is based on insertion sort, except that insertion sort is only compared with the previous element at a time, and now it is compared with The elements with an interval of h in the front are compared, and after each comparison, the range of h is reduced and then the insertion sort is continued to be compared to achieve the purpose of sorting.

Based on this: (1) Because the range to be sorted is controlled by h, it becomes particularly important how to set the size of h by mathematical formulas or what kind of function expressions are designed (this is also his instability In general, the more data there is, the larger the interval will be at the beginning (the interval can be calculated so that the interval is the distance from the middle to the previous element, and then decreases until the interval is 1, as shown below The ten data are sorted by Hill with h interval of 4)

package csnd;

public class Arrash {
	int array[];
	int nElems;
	public Arrash() {
		nElems = 0;
	}
	public Arrash(int n)
	{
		array = new int[n];
		nElems = 0;
	}
	public void insert(int j) {
		array [nElems] = j;
		nElems++;//Note that when the last element is inserted, the nElems value will also increase by one
	}
	public void display(){
		for(int i=0;i<nElems;i++)
			System.out.print(array[i]+" ");
		
		System.out.println();
	}
	public void shellSort() {
		int inner,outer;
		int temp;
		int h=1;
		while(h<=nElems/3)
			h = h*3+1;
		while(h>0)
		{
			for(outer=h;outer<nElems;outer++)
			{
				inner = outer;
				temp = array[outer];
				while(inner>h-1&&array[inner-h]>=temp)//Keep the array basically ordered until the last order
				{
					array[inner]=array[inner-h];
					inner -=h;
				}
				array[inner] = temp;
			}
			h = (h-1)/3;
		}

	}
	public static void main(String[] args) {
		Arrash theArray = new Arrash(10);
		for(int i=0;i<10;i++)
		{
			int n=(int)(Math.random()*(10));
			theArray.insert(n);
		}
		System.out.println("Array before sorting");
		theArray.display();
		System.out.println("sorted array");
		theArray.shellSort();
		theArray.display();
	}
}
result:
array before sorting
6 4 9 2 4 0 1 2 6 1 
sorted array
0 1 1 2 2 4 4 6 6 9 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325902982&siteId=291194637