Package utils.sort;
/**
* Hill sort, requires that the array to be sorted must implement the comparable interface
*/
public class Shellsort implements Sortstrategy
{
Private int[] increment;
/**
* Using the hill sort algorithm to sort the array obj
*/
public void sort (comparable[] obj)
{
if (obj = null)
{
throw new NullPointerException ("The argument can not be null!");
}
Initialization step
Initgap (obj);
Step changes in descending order (descending)
for (int i = increment.length-1 i >= 0; i--)
{
int step = Increment[i];
Start by step position
for (int j = Step; J < Obj.length; J + +)
{
comparable TMP;
If the following is less than the previous (step by step), the exchange with the preceding
for (int m = j; M >= step; m = m-step)
{
if (Obj[m].compareto (Obj[m-step]) < 0)
{
TMP = Obj[m-step];
Obj[m-step] = obj[m];
OBJ[M] = tmp;
}
Because the previous position must have been compared, so here's a direct exit loop
Else
{
Break
}
}
}
}
}
/**
* Determine the maximum exponent of the formula for increment based on the length of the array, the formula is POW (4, I)-3 * POW (2, I) + 1 and 9 * POW (4, i)-9 * POW
2, i) + 1
* @return int[] maximum exponent of two formulas
* @param length of array
*/
Private int[] initexponent (int length)
{
Int[] exp = new INT[2];
Exp[0] = 1;
EXP[1] =-1;
Int[] gap = new INT[2];
Gap[0] = gap[1] = 0;
Determine the maximum exponent of a two formula
while (Gap[0] < length)
{
exp[0]++;
GAP[0] = (int) (Math.pow (4, exp[0])-3 * MATH.POW (2, exp[0]) + 1);
}
exp[0]--;
while (Gap[1] < length)
{
exp[1]++;
GAP[1] = (int) (9 * MATH.POW (4, exp[1])-9 * MATH.POW (2, exp[1]) + 1);
}
exp[1]--;
return exp;
}
private void Initgap (comparable[] obj)
{
Initializing an incremental sequence with a formula
int exp[] = initexponent (obj.length);
Int[] gap = new INT[2];
increment = new Int[exp[0] + exp[1]];
To assign an incremental array from a large to a small value
for (int i = exp[0] + exp[1]-1; I >= 0; i--)
{
GAP[0] = (int) (Math.pow (4, exp[0])-3 * MATH.POW (2, exp[0]) + 1);
GAP[1] = (int) (9 * MATH.POW (4, exp[1])-9 * MATH.POW (2, exp[1]) + 1);
Put large increments first into an incremental array, which is actually a merge sort
There is no need to consider the case of gap[0] = = gap[1], because equality cannot occur.
if (Gap[0] > Gap[1])
{
Increment[i] = gap[0];
exp[0]--;
}
Else
{
Increment[i] = gap[1];
exp[1]--;
}
}
}
}