max diff for pairs in an array

#include<stdio.h>

int maxDiff( int *array, unsigned length );
int getDiff( int *start, int *end, int **max, int **min );

int main( void )
{
    int num[] = { 2, 4, 1, 16, 7, 5, 11, 9 };
    //int num[] = { 2, 4, 1};
    int *arr = num;

    int result = maxDiff( arr, sizeof( num ) / sizeof(int) );

    printf( "%d\n", result );
    return 0;
}

int maxDiff( int *num, unsigned length )
{
    int *max ;
    int *min;

    if( length < 2 )
    {
        return -1;
    }
    else if( length == 2 )
    {
        return *num >= *( num + 1 ) ? ( *num - *( num + 1 ) ) : ( *( num + 1 ) - *num );
    }
    return getDiff( num, num + length-1, &max, &min );

}

int getDiff( int *start, int *end, int **max, int **min )
{
    if( start == end )
    {
        *max = *min = start;
        return 0;
    }
    int *mid = start + ( end - start )/2;

    int *minLeft, *maxLeft;
    int leftDiff = getDiff( start, mid, &maxLeft, &minLeft );
    int *maxRight, *minRight;
    int rightDiff = getDiff( ( mid + 1 ), end, &maxRight, &minRight );

    *max = *maxLeft > *maxRight ? maxLeft : maxRight;
    *min = *minLeft < *minRight ? minLeft : minRight;

    int crossDiff = *maxLeft - *minRight;

    int maxDiff = leftDiff > rightDiff ? leftDiff : rightDiff;
    maxDiff = maxDiff > crossDiff ? maxDiff : crossDiff;

    return maxDiff;

}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s