-3

我正在编写排序算法——Shellsort。错误在哪里?

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;
}
4

1 回答 1

1

内循环中的条件,

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

导致算法甚至看不到ai_numbers[0]. 该算法似乎在编写时考虑到了基于 1 的数组索引。

循环控制应该是

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

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

正确地纳入ai_numbers[0].

于 2012-10-29T15:22:19.860 回答