I'm programming sorting algorithm - Shellsort. Where is bug?

177 Views Asked by At

I'm programming sorting algorithm — Shellsort. Where is bug?

int shellsort( int ai_numbers[], const int ci_count ){

    int i, j, temp, counter = 0, inc;
    inc = ci_count / 2;

    while ( inc > 0 )
    {
        for ( i = inc + 1; i < ci_count ; i++)
        {
            temp = ai_numbers[i];
            j = i;

            while ( j > inc && ai_numbers[j - inc] > temp )
            {
                ai_numbers[j] = ai_numbers[j - inc];
                j = j - inc;
                counter++;
            }
            ai_numbers[j] = temp;
        }

        inc = (int) (inc / 2.2);
    }
    return counter;
}
1

There are 1 best solutions below

0
On

The condition in the inner loop,

while ( j > inc && ai_numbers[j - inc] > temp )

causes the algorithm to never even look at ai_numbers[0]. The algorithm seems to be written with 1-based array indices in mind.

The loop controls should be

for ( i = inc; i < ci_count ; i++)

and

while ( j >= inc && ai_numbers[j - inc] > temp )

to properly incorporate ai_numbers[0].