PROGRAM:
Given an array find 3 elements such that a[i] < a[j] < a[k] and i < j < k in 0(n) time.
NOTE :
It finds every possible such combination.
SOLTUION:
#include "iostream.h"
#include "cstdio"
#include "cstdlib"
#include "unistd.h"
#include "vector.h"
using namespace std;
void print(vector<int> a1, int i, int j, int k)
{
cout<<"\n\nThe element starts at position : "<i;
cout<<"\nThe elements are : "<a1[i]
<" "
<a1[j]
<" "
<a1[k];
}
int main()
{
vector<int> a;
int i=0;
int flag=1;
int j=0;
int first=0;
int mid=0;
int last=0;
int k=0;
int num=0;
//loop for entering values.
cout<<"\n\nEnter numbers : \n";
cout
<<"(Enter value other than integer to stop entering value)\n\n";
while(true)
{
cout
<endl
<endl;
cin>>num;
if(cin.good())
{
a.push_back(num);
continue;
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout<<"\n\n You enetered non itegral value....Evaluating Array \n\n";
break;
}
}
int size = a.size();
cout<
if(size < 3)
{
cout<<"\n\nArray has less than 3 elements\n\n";
exit(0);
}
//loop to find elements
while(i < size )
{
first = a[j];
if(i != j)
{
//setting mid value only if none of the secod is found.
if(a[i] > first && k==0)
{
mid = a[i];
k=i;
}
else if(a[i] > mid && k!=0)
{
last = a[i];
flag=0;
print(a,j,k,i);
if( k < size-2)
{
i=++k;
k=0;
}
else
{
i=++j;
k=0;
}
continue;
}
//checking for finding mid element to further position of k, if at that case 3rd element was not found.
if( i == size-1 && j < size-3)
{
if(k < size-2 && k!=0)
{
i=++k;
k=0;
continue;
}
else
{
//changing the first value only if no second value is availaible wrt a[j].
i=++j;
k=0;
continue;
}
}
}
i++;
}
if(flag != 0)
{
cout<<"\n\n Such elements dont exist in the array \n\n";
}
}

Whats the time complexity ?
ReplyDelete