Shellsort Interval Question Java
I need to test the efficiency of shellsort when I am using the standard interval size and also while using a non-standard size. The problem I am encountering is when I try to use my non-standard inte开发者_JAVA百科rval.
This is my Shellsort when h is equal to the standard interval size:
public void shellSort()
{
int inner, outer;
int temp;
int h = 1;
while (h <= length / 3)
{
h = h * 3 + 1;
}
while (h > 0)
{
for (outer = h; outer < length; outer++)
{
temp = data[outer];
inner = outer;
while (inner > h - 1 && data[inner - h] >= temp)
{
data[inner] = data[inner - h];
inner -= h;
}
data[inner] = temp;
}
h = (h - 1) / 3;
}
}
And here is my attempt at using a prime number interval
private int[] primes = {0, 1, 3, 7, 13, 31, 97, 211, 503, 1013, 2503, 5171};
public void shellSort()
{
int inner, outer;
int temp;
int count = this.h.length - 1;
int h = 1;
h = primes[primes.length - 1] * 2 > length ? primes[primes.length - 1] : primes[primes.length - 2];
while (h > 0)
{
for (outer = h; outer < length; outer++)
{
temp = data[outer];
inner = outer;
while (inner > h - 1 && data[inner - h] >= temp)
{
data[inner] = data[inner - h];
inner -= h;
}
data[inner] = temp;
}
if(count - 1 > 0)
h = primes[count - 1];
}
}
I am trying to compare the two based off of real time efficiency , and I can't figure out how to get this prim interval to work.
I'm trying to test:
- Shellsort performs better than O(N^2) with appropriately chosen interval sizes
- The series of interval sizes chosen is important to achieving better than O(N^2) runtime
Thank you for any help.
You probably want to decrement the value of count
in each iteration of the outer loop. In your code it is still this.h.length-1
, which is 11. Therefore, after each iteration of the outer loop you have the if
condition count-1 > 0
satisfied, so you set h = this.h[count-1]
, which I believe is 2503. So, you reenter the loop.
By the way, calling the list of interval sizes h
seriously impedes readability. You should call it at least hs
.
精彩评论