Skip to content

Commit

Permalink
Merge pull request #50 from octamois/master
Browse files Browse the repository at this point in the history
 Added Ternaray Search C++ code
  • Loading branch information
srbcheema1 authored Oct 1, 2017
2 parents df885b6 + ed3b138 commit 7fa2fe1
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Searching Algorithms/ternarySearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//Ternary Search Uses Divide And Conquer Technique
#include<iostream>

/*
* Part of Cosmos by OpenGenus Foundation
*/

using namespace std;
int ternarySearch(int arr[],int l,int r, int x){
if(r>=l){
int mid1 = l + (r-l)/3;
int mid2 = r - (r-l)/3;
if(arr[mid1] == x)
return mid1;
/*
In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd part of array
*/
if(arr[mid2] == x)
return mid2;
if(x<arr[mid1])
return ternarySearch(arr,l,mid1-1,x);
else if(x>arr[mid2])
return ternarySearch(arr,mid2+1,r,x);
else
return ternarySearch(arr,mid1+1,mid2-1,x);
}
return -1; // if x is not found in array arr
}
int main(){
int arr[] = {1, 2, 3, 5};
int size = sizeof(arr)/ sizeof(arr[0]);
int find = 3;
cout<<"Position of "<<find<<" is "<<ternarySearch(arr,0,size-1,find);
return 0;
}

0 comments on commit 7fa2fe1

Please sign in to comment.