Find if there is a pair in the array which sums to a value N

#include <stdio.h>
#include <stdlib.h>

#define N 10

void quickSort(int *A, int first, int last)
{
    int pivot,i,j,temp;

    if(first >=last) return;

    pivot = first;
    i     = first;
    j     = last;
    
    while(i < j)
    {
       while (A[i] <= A[pivot]) i++;
       while (A[j] >  A[pivot]) j--;
       
       if(i < j)
       {
          temp = A[i];
          A[i] = A[j];
          A[j] = temp;
       }
    }
    
    temp     = A[pivot];
    A[pivot] = A[j];
    A[j]     = temp;
    
    quickSort(A, first, j-1);
    quickSort(A, j+1, last);
}


int hasArrayGotThisNumber(int *A, int val)
{
    int i,m,n;
    m = 0;
    n = N-1;
    
    while(m < n)
    {
        if      ((A[m]+A[n]) == val)
        break;

        else if ((A[m]+A[n]) < val)
        m++;

        else if ((A[m]+A[n]) > val)
        n--;
    }
    
    if(m < n)
       return 1;
    else
       return 0;
}

int main(void)
{
    int result = 0,i;
    int A[N] = {34,1,6,2,7,66,67,238,53,2};
    
    //First sort the array.
    quickSort(A,0,N-1);

    //Now find if the array has got the required pair.
    result = hasArrayGotThisNumber(A, 67);
    
    printf("%d\n",result);
    
    return 0;
}

No comments:

Post a Comment