0

I know this has been posted before but I tried to do on my way I tried to code but which is showing erroneous result! obviously there is error in my logic..can anyone please explain me where am I having error?

here we are assuming that arrays are sorted in descending order!

int kthlargestsum(int a[], int b[],int k)
{
    int aIndex=0;
    int bIndex=0;
    int sum=0;
    int i;
    for(i=0;i<k;++i)
    {
        if(a[aIndex]>b[bIndex])
        {
            sum+=a[aIndex];
            ++aIndex;
        }
        else
        {
            sum+=a[bIndex];
            ++bIndex;
        }
    }
printf("the output is %d",sum);
}

main()
{
    int a[]={10,9,6,4,2};
    int b[]={11,9,7,1};
    int k;
    printf("enter the value of k \n");
    scanf("%d",&k);
    kthlargestsum(a,b,k);

}
learning_bee
  • 165
  • 7
  • 18
  • Read and understand the solution(s) to this question: http://stackoverflow.com/questions/5212037/find-the-kth-largest-sum-in-two-arrays – PengOne Aug 19 '11 at 00:03

1 Answers1

0

First off, a[bIndex] seems suspect to me. Perhaps you want b[bIndex]?

For anything else, you'll have to be more clear on what the problem you're trying to solve actually is (examples are always nice:). What you code appears to do is to add up k entries from the two arrays. This is now how I would interpret "Find kth largest of sum of elements in 2 array".

PengOne
  • 48,188
  • 17
  • 130
  • 149
  • let say k=3..so 3rd largest sum will 19…it ll be as follows-1st-10+11,2nd-11+9,3rd-10+9 – learning_bee Aug 18 '11 at 23:46
  • @learning_bee: you seem to be assuming that the arrays are sorted into descending order. If that is indeed the case, then please edit your question to reflect that crucial assumption. Also, in that case, my above correction will fix your code. – PengOne Aug 18 '11 at 23:48
  • @learning_bee well if you go: 10+11, 9+11, 10+9... then you actually decreased aIndex (which would never happen in your program). – Konrad Morawski Aug 18 '11 at 23:58
  • @learning_bee: Think about what `for(i=0;i – PengOne Aug 18 '11 at 23:59