Friday, January 1, 2010

for programming interviews part 7

hi today we shall discuss the problem related to arrays
12.how to left roate an array
#include < iostream >
int main()
{
using namespace std;
int a[5]={3,4,5,1,2};
int k=5,temp=0,i;
for(i=k;i < 5 ;++i)
{

temp=a[i];
a[i]=a[i-k];
a[i-k]=temp;
}
for(i=0;i < 5;++i)
cout << a[i] << endl;
cin.sync();
cin.get();
return 0;
}
14.how to find element in sorted array which is rotated in O(logn)

#include < iostream >
int main()
{
using namespace std;
int a[5]={2,3,4,5,1};
int mid=0,l=0,r=4,key=5;
while(l<=r)
{
mid=l+(r-l)/2;
if(a[mid]==key)
{
cout << mid;
break;
}
if(a[l] > a[mid])
{
if((key > a[mid])&&(key < a[l]))
l=mid+1;
else
r=mid-1;
}
else if(a[r] < a[mid])
{
if((key > a[r])&&( key < a[mid]))
r=mid-1;
else
l=mid+1;
}
else if(key < a[mid])
r=mid-1;
else
l=mid+1;
}



cin.sync();
cin.get();
return 0;
}

16.how to find product of elements in arrray for ith element the product shlould be all the element except ith element without using / operator

#include < iostream >
int main()
{
using namespace std;
int arr[5]={1,2,3,4,5};
int i=0,l=1,r=1;
int res[5]={1,1,1,1,1};
for(i=0;i < 5;++i)
{
res[i]*=l;
res[4-i]*=r;
l*=arr[i];
r*=arr[4-i];
}
for(i=0;i<5;++i)
cout << res[i] << endl;
cin.sync();
cin.get();
return 0;
}

No comments:

Post a Comment