Search code examples
algorithmlanguage-agnosticinfinite-loophalting-problem

Will this algorithm terminate?


With different values in a collection, will this algorithm (pseudeocode) ever terminate?

while (curElement != average(allElements))
{
    curElement = average(allElements);
    nextElement();
}

Note that I'm assuming that we will re-start from the beginning if we're at the end of the array.


Solution

  • Since this is pseudocode, a simple example with 2 elements will reveal that there are cases where the program won't terminate:

    x = 0, y = 1;
    
              x     y
    Step 1:   0.5   1
    Step 2:   0.5   0.75
    Step 3:   0.635 0.75
    //and so one
    

    With some math involved, lim(x-y) = lim( 1 / 2^n )

    So the numbers converge, but they're never equal.

    However, if you'd actually implement this on a computer, they will turn out equal because of hardware limitations - not all numbers can be expressed in a limited number of bits.