maximum, minimum, mean, and median of the data set. in array c programming code example

Example 1: maximum, minimum, mean, and median of the data set. in array c programming

int[] findMinMax(int A[], int n)
{
    int max, min
    int i
    if ( n is odd )
    {
        max = A[0]
        min = A[0]
        i = 1
    }
    else
    {
        if ( A[0] < A[1] )
        {
            max = A[1]
            min = A[0]
        }
        else
        {
            max = A[0]
            min = A[1]
        }
        i = 2
    }
    while ( i < n )
    {
        if ( A[i] < A[i+1] )
        {
            if ( A[i] < min )
                min = A[i]
            if ( A[i+1] > max )
                max = A[i+1]
        }
        else
        {
            if ( A[i] > max )
                max = A[i]
            if ( A[i+1] < min )
                min = A[i+1] 
        }
        i = i + 2
    }
    // By convention, we assume ans[0] as max and ans[1] as min
    int ans[2] = {max, min}
   return ans
}

Example 2: maximum, minimum, mean, and median of the data set. in array c programming

T(n) = 2 T(n/2) + 2
T(2) = 1
T(1) = 0
We can solve this recurrence relation by master method/recursion tree method.
if n is a power of 2
T(n) = 3n/2 - 2

Example 3: maximum, minimum, mean, and median of the data set. in array c programming

int[] findMinMax(int A[], int start, int end)
{
    int max;
    int min;
    if ( start == end )
    {
        max = A[start]
        min = A[start]
    }
    else if ( start + 1 == end )
    {
        if ( A[start] < A[end] )
        {
            max = A[end]
            min = A[start]
        }
        else
        {
            max = A[start]
            min = A[end]
        }
    }
    else
    {
        int mid = start + (end - start)/2
        int left[] = findMinMax(A, start, mid)
        int right[] = findMinMax(A, mid+1, end)
        if ( left[0] > right[0] )
            max = left[0]
        else
            max = right[0]
        if ( left[1] < right[1] )
            min = left[1]
        else
            min = right[1]
    }
    // By convention, we assume ans[0] as max and ans[1] as min
    int ans[2] = {max, min}
   return ans
}

Tags:

Misc Example