Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Ternary Search code[C++] #541

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
76 changes: 76 additions & 0 deletions ternary_search/ternary_search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include <iostream>

using namespace std;
/*
* Function implementing ternary search
* args:
* ar : Initial array containing elements (unsorted)
* n : the search tree's depth
* left : left index of array.
* right : right index of array.
* x : element to be searched.
* Time Complexity : O(max(input))
*/
int ternary_search (int ar[],int n, int left, int right, int x)
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please follow Google C++ Style Guide,

function(param) {
    if(condition) {
    }
}


if(left < 0 || right > n-1 || left > right)
{
return -1;
}
if(x == ar[left])
{
return left;
}

if(x == ar[right])
{
return right;
}

// Update the two index left and right if the element is not found.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put comments above the relevant blocks and remove unnecessary blank lines.



if(x < ar[left])
{
return ternary_search(ar,n,left-1,right,x);
}

if (x > ar[left] && x < ar[right])
{

return ternary_search(ar,n,left+1,right-1,x);
}

if(x > ar[right])
{
return ternary_search(ar,n,left,right+1,x);
}
}


int main()
{
int s = 12;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indent correctly.

int v[s];
short x;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use common english words instead of single letter variable names.

for(int i = 1; i <= s; i++)
{
v[i-1] = i;
}
cout << "Enter number for research:\n";
cin >> x;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't ask for any input, take any sample value.


int left = s/3;
int right = (s/3)*2;

if(ternary_search(v,s,left-1,right-1,x) == -1)
{
cout<<"Number does not exist in array.\n";
}
else
{
cout<<"The index is:"<<ternary_search(v,s,left-1,right-1,x)<<"\n";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put space around << and all binary operators.

}
return 0;
}