Thursday, February 19, 2015

Floor and Ceiling in a sorted array


Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume than the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x.
For example, let the input array be {1, 2, 8, 10, 10, 12, 19}
For x = 0:    floor doesn't exist in array,  ceil  = 1
For x = 1:    floor  = 1,  ceil  = 1
For x = 5:    floor  = 2,  ceil  = 8
For x = 20:   floor  = 19,  ceil doesn't exist in array



// Code starts here ,, I used linear search to search the element.


#include<stdio.h>

void fun(int *arr,int arrSize,int *floor,int *ceil,int ele);

int main(void)
{

int arr[] ={1, 2, 8, 10, 10, 12, 19};
int arrSize=sizeof(arr)/sizeof(arr[0]);
int i=0,floor=-1,ceil=10000;

fun(arr,arrSize,&floor,&ceil,9);

if(floor==-1)
{
printf("no floor existsss...");
printf("ceil at indeX==%d\n",ceil);

}
else if(ceil==10000)
{
printf("floor at indeX==%d\n",floor);
printf("no ceil existsss...");
}
else
{
printf("floor at indeX==%d\n",floor);
printf("ceil at indeX==%d\n",ceil);
}

return 0;

}


void fun(int *arr,int arrSize,int *floor,int *ceil,int ele)
{
int i=0,flag=0;
while(i<arrSize)
{
if(ele==arr[i])
{
*floor=i;
*ceil=i;
flag=1;
}
else if(ele>arr[i])
{
*floor=i;
}
else
{
*ceil=i;
flag=1;
}

if(flag==1)
{
break;
}


i++;
}


}

No comments:

Post a Comment