Friday, July 19, 2013

Find a pair of elements from an array whose sum equals a given number

 
 /*  
  * 1.Given a sorted array a and a sum k print 
  * all pairs of indexes i and  j such that 
  * a[i]+a[j]=k.  
  */  

 void printPairsWithSum(int *array, int k, int len) {
      int startIndex = 0, endIndex = len - 1, sum;
      while (startIndex < endIndex) {  
           sum = array[startIndex] + array[endIndex];
           if (sum == k) {  
                printf("%d %d \n", startIndex, endIndex);
                startIndex++;  
           } else if (sum > k)  
                endIndex--;  
           else  
                startIndex++;  
      }  
 }  
 int main() {  
      int *array = malloc(sizeof(int) * 100);  
      int len, i;  
      scanf("%d", &len);  
      for (i = 0; i < len; i++) {  
           scanf("%d ", &array[i]);  
      }  
      printPairsWithSum(array, 12, len);  
      return 0;  
 }  

No comments:

Post a Comment