0

An array contains integers that first increase in value and then decrease in value. It is unknown at which point the numbers start to decrease. Write efficient code to copy the numbers in the first array to another array so that the second array is sorted in ascending order.

The code is below:

int _tmain(int argc, _TCHAR* argv[])
{
    int a[10] = { 17, 24, 31, 39, 44, 49, 36, 29, 20, 18 };
    int b[10];

    int i = 0, j = 9, k = 0;

    while (i <= j) {
        if (a[i] < a[j]) {
            b[k++] = a[i++];
        }
        else {
            b[k++] = a[j--];
        }
    }

    return 0;
}

What is the loop invariant here?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Abhiram
  • 355
  • 1
  • 7

2 Answers2

1

A loop invariant is something that holds true before and after each iteration of your loop. This includes after the loop terminates and before it begins. There are quite a few of them, although most of them are not important. You will want to pick one that helps prove the algorithm is correct. A loop invariant for that would be:

The sub-array b of length k consists of the items from array a, but in sorted order.

When proving this invariant you will want to show for the array b that element i+1 is larger than element i.

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
  • To reflect this invariant better, perhaps i should have k = -1 as the initialization and b[++k] in the assignments – Abhiram May 28 '15 at 04:54
  • @Abhiram `k` going to `10` does pose a problem (same idea nonetheless). If you want I could change it to "sub-array of length *k*", that would work and reflect your code, but will be bit more abstract. – Spencer Wieczorek May 28 '15 at 05:00
0

The invariant is the condition in the while loop, so i <= j.

an invariant of a loop is a property that holds before (and after) each repetition

Source: wiki

Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20