In this post,I demonstrate a problem which is asked in zoho interviews.
So, i think tis will be usefull for the people who are preparing for their
job interviews.
Question:
Find immediate greater in an array
An array of 'n' elements is given,
immediate greater element for every element should be found in the array.
Input:
6 4 3 9 5
Output:
6->9 4->5 3->4 9-> 5->6
Algorithm:
1.Get the elements in an array.
2.Sort the elemens in the separate another array.
3.Take an element in unsorted array and find its position in
sorted array and its next element is its immediate greater.
4.Do the same process for all elements.
5.If its positiion in sorted array is n-1,then it do not have
any greater element to it.
Program:
#include<stdio.h>
#include<conio.h>
int arr[50],sort[50],n;
int search(int a);
void sorting();
void main()
{
int i,j;
clrscr();
printf("Enter no. of elements in the array\n");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
sort[i]=arr[i];
}
sorting();
for(i=0;i<n;i++)
{
j=search(arr[i]);
if(j+1==n){printf("%d->\t",arr[i]);}
else
printf("%d->%d\t",arr[i],sort[j+1]);
}
getch();
}
void sorting()
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(sort[i]>sort[j])
{ temp=sort[i];
sort[i]=sort[j];
sort[j]=temp;
}
}
}
return;
}
int search(int a)
{
int i;
for(i=0;i<n;i++)
{
if(a==sort[i])
return i;
}
}
Hope you understand the problem and the solution for it.
Any questions or complexity in explanation ask in comments.
Thank you.

No comments:
Post a Comment