I am working on to find the k
th smallest element in min heap. I have got a code for this whose complexity is O(k log k)
. I tried to improve it to O(k)
.
Below is the code.
struct heap{
int *array;
int count;
int capacity;
};
int kthsmallestelement(struct heap *h,int i,int k){
if(i<0||i>=h->count)
return INT_MIN;
if(k==1)
return h->array[i];
k--;
int j=2*i+1;
int m=2*i+2;
if(h->array[j] < h->array[m])
{
int x=kthsmallestelement(h,j,k);
if(x==INT_MIN)
return kthsmallestelement(h,m,k);
return x;
}
else
{
int x=kthsmallestelement(h,m,k);
if(x==INT_MIN)
return kthsmallestelement(h,j,k);
return x;
}
}
My code is traversing k
elements in heap and thus complexity is O(k)
.
Is it correct?