문제

I am writing a program that implements the insertion sort algorithm to sort an array:

 public void insertionSort()
{
    int in, out;

    for (out = 1; out < nElems; out++)     // out is dividing line
    {
        copies++;                       
        long temp = a[out];            // remove marked item
        in = out;                      // start shifts at out
        while (in > 0 && a[in - 1] >= temp) // until one is smaller,
        {
            a[in] = a[in - 1];            // shift item to right
            --in;                       // go left one position
            ++comparissons;             
        }
        a[in] = temp;                  // insert marked item
    }  // end for
}  // end insertionSort(

I am also implementing counters that count how many comparisons are made during the course of the algorithm. in my while loop:

 while (in > 0 && a[in - 1] >= temp) // until one is smaller,
    {
        a[in] = a[in - 1];            // shift item to right
        --in;                       // go left one position
        ++comparissons;             
    }

two comparison are made, that means for those two comparison the 'comparissons' variable is only incremented by one (even though TWO comparisons are actually made).

My question is: how do I break down this while loop with two comparison into two parts so I can increment 'comparissons' each time a comparison is actually made while retaining the same functionality.

Thanks!

JLL

도움이 되었습니까?

해결책

Are you referring to the comparisons in the while condition? If yes, just check those conditions separately

while (in > 0) // until one is smaller,
{
    ++comparissons; 
    if (a[in - 1] >= temp)   ++comparissons;
    else                     break;

    a[in] = a[in - 1];            // shift item to right
    --in;                       // go left one position           
}

다른 팁

Move the comparison into an if inside the while loop.

while (in > 0) {
    // Move the comparison increment here.
    if (a[in -1] >= temp) {
       // The rest of the original while code here.   
    } else {
       break;
    }
}

Or you can do a hack like this and move the comparisons increment into the condition itself.

while (in > 0 && ((a[in-1] >= temp) && (++comparisons > -1))) {
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top