Trinary Search

I am trying to convert a binary search into a trinary search. I have to keep both functions in the program, and I cannot figure out how to continue on to the trinary search after the binary has completed.
How does a trinary search work, exactly? I've never heard of it.
It is just a function that searches for a user given number in a list. It is just like a modified binary search. The list is divided into 3 parts instead of 2.
I did ternary with a stroke of intelligence. Seriously, I didn't know how to do it and I just typed it down and it WORKED!!!!! OMG IT WORKED!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

void binary(int digit)
{
    int pass = digit;
    int number = 256;
    for(int i = 0;i < 9;i++)
    {
        if(pass >= number)
        {
            cout << "1";
            pass = pass - number;
        }
        else
        {
            cout << "0";
        }
        number = number / 2;
    }
    cout << endl;
}

void ternary(int digit)
{
    int pass = digit;
    int number = 6561;
    for(int i = 0;i < 9;i++)
    {
        if(pass / number == 2)
        {
            cout << "2";
            pass = pass - number;
        }
        else if(pass / number == 1)
        {
            cout << "1";
            pass = pass - number;
        }
        else
        {
            cout << "0";
        }
        number = number / 3;
    }
    cout << endl;
}

int main(int nNumberofArgs,char* pszArgs[])
{
    int digit;
    cout << "Enter number to be translated into binary and ternary: ";
    cin >> digit;

    binary(digit);
    ternary(digit);
    system("PAUSE");
    return 0;
}
Ah; ternary != trinary
Thank you, but I am looking for a TRINARY function. Ternary is a completely different thing.
I am trying to convert this code into a trinary search:

int searchlist(const int list[], int numElems, int value)
{
int first = 0,
last = Max -1,
middle,
position = -1;
bool found = false;

while ( !found && first <= last)
{
middle = (first + last) /2;
if (list[middle] == value)
{
found = true;
position = middle;
}
else if (list[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
please do code tages
Last edited on
ah, well, never mind, my ternary function has a few run time bugs. It doesn't ternary some numbers correctly... such as 25, 16...
Topic archived. No new replies allowed.