sagar
sagar

Reputation: 801

Finding the distance between the two closest numbers in an array of n numbers. (Presorted Arrays)

The arrays are presorted making the algorithm θ(nlogn) [sorting+finding minimum distance], compared to bruteforce θ(n2). Both the codes does the same job but the first one shows time limit exceeded. I wonder what the error is. Any bug in the code?

Code with while loop (time limit exceeded)


#include <stdio.h>

void mindistance(int a[],int n)
{
    int i=1,arraymin=999,currentmin,current=a[0];

    while(i<n)
    {
        if(a[i]==current)
            i++;
        else
        {
            currentmin=a[i]-a[i-1];
            if(currentmin<arraymin)
            {
                arraymin=currentmin;
                current=a[i];
                i++;
            }

        }
    }
    printf("%d",arraymin);
}


int main(void)
{

    int a[]={4,34,56,77,99,424,754}; 
    mindistance(a,7);

    return 0;
}

Code using for loop (works well)


#include <stdio.h>

void mindistance(int a[],int n)
{
    int i,arraymin=999,currentmin,current=a[0],x,y;

    for(i=1;i<n;i++)
    {
        if(a[i]==current)
            continue;
        else
        {
            currentmin=a[i]-a[i-1];
            if(currentmin<arraymin)
            {
                arraymin=currentmin;
                current=a[i];

            }

        }
    }
    printf("%d",arraymin);
}


int main(void)
{

    int a[]={4,34,56,77,99,424,754};
    mindistance(a,7);

    return 0;
}

Upvotes: 1

Views: 1150

Answers (2)

oded betzalel
oded betzalel

Reputation: 233

Loops are not identical. In the for loop i is increased in each iteration, while in the while loop i is increased only in some cases. An identical while loop would be:

while(i<n)
{
    if(a[i]==current)
        i++;
    else
    {
        currentmin=a[i]-a[i-1];
        if(currentmin<arraymin)
        {
            arraymin=currentmin;
            current=a[i];
        }
        i++;
    }
}

Upvotes: 1

Saleac
Saleac

Reputation: 1

I believe you're getting caught in an infinite loop because you aren't setting currents value every iteration.

Upvotes: 0

Related Questions