Question

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

Was it helpful?

Solution

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           
}

OTHER TIPS

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))) {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top