Shell Sort Algorithm, Program timing out C++

150 Views Asked by At

It tells me my program has timed out. The insertionSortInterleaved function works great, but when I try to enter gap values the program times out. Please help

void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap)
{
    int i = 0;
    int j = 0;
    int temp = 0;  // Temporary variable for swap

    for (i = startIndex + gap; i < numbersSize; i = i + gap)
    {
        j = i;
        while (j - gap >= startIndex && numbers[j] < numbers[j - gap])
        {
            temp = numbers[j];
            numbers[j] = numbers[j - gap];
            numbers[j - gap] = temp;
            j = j - gap;
        }
    }
}

void ShellSort(int numbers[], int numbersSize, int gapValues[], int numGaps)
{
    for (int i = 0; i < numGaps; i++)
    {
        int gapValue = gapValues[i];
        for (int j = 0; j < gapValue; i++)
        {
            insertionSortInterleaved(numbers, numbersSize, i, gapValue);
        }
    }
}
1

There are 1 best solutions below

0
Valeca On

It might be just because you need to wrap j - gap in brackets, otherwise the operators precedence is different from what you want. Something like this:

while ( (j - gap) >= startIndex && numbers[j] < numbers[j - gap])

Also, it looks like adding the check that (j-gap) is a valid range makes sense as well.