I have code which counts the number of comparison of binary ternary and quad trees what i think the code for ternary and quad trees
fixDown3 and fixDown4 are off. If you test them on some data (say run a heapSort based on them, you'll see that your positional expressions are all off).
For example, take a look at fixDown4.
template <class Item>
void fixDown4(Item a[], int k, int N)
{ int j;
while (3*k <= N)
{ c1++;
j = 4*k;
if (j < N)
{ if (a[4*k-2]>a[j]) j-=2;
if (a[4*k-1]>a[j]) j=4*k-1;
if (a[4*k+1]>a[j]) j++;
}
if (!(a[k]< a[j])) break;
exch(a[k], a[j]); k = j;
}
}
The expression 3*k <= N for testing internal nodes is wrong. Check it out on some quad-tree with the heap4 numbering.
The expression j = 4*k; won't give you the left-most brother and hence the expression j<N would cut out some nodes. The comparison in
if (a[4*k-2]>a[j]) j-=2;
if (a[4*k-1]>a[j]) j=4*k-1;
if (a[4*k+1]>a[j]) j++;
are completely off when you have only one or two brothers.
heres the code
#include <iostream>
using namespace std;
int c2=0, c3=0, c4=0;
template <class Item>
void exch(Item &A, Item &B)
{ Item t = A; A = B; B = t; }
template <class Item>
void fixDown(Item a[], int k, int N)
{ int j;
while (2*k <= N)
{ c2++;
j = 2*k;
if (j < N && a[j]< a[j+1]) j++;
if (a[k]>= a[j]) break;
exch(a[k], a[j]); k = j;
}
}
template <class Item>
void heapsort(Item a[], int l, int r)
{ int k, N = r-l+1;
for (k = N/2; k >= 1; k--)
fixDown(&a[0], k, N);
while (N > 1)
{
exch(a[1], a[N]);
fixDown(&a[0], 1, --N);
}
}
template <class Item>
void fixDown3(Item a[], int k, int N)
{ int j;
while (3*k <= N)
{ c3++;
j = 3*k;
if (j < N)
{ if (a[3*k-1]>a[j]) j--;
if (a[3*k+1]>a[j]) j++;
}
if (!(a[k]< a[j])) break;
exch(a[k], a[j]); k = j;
}
}
template <class Item>
void heapsort3(Item a[], int l, int r)
{ int k, N = r-l+1;
for (k = (N+1)/3; k >=1; k--)
fixDown3(&a[0], k, N);
while (N > 1)
{
exch(a[1], a[N]);
fixDown(&a[0], 1, --N);
}
}
template <class Item>
void fixDown4(Item a[], int k, int N)
{ int j;
while (3*k <= N)
{ c4++;
j = 4*k;
if (j < N)
{ if (a[4*k-2]>a[j]) j-=2;
if (a[4*k-1]>a[j]) j=4*k-1;
if (a[4*k+1]>a[j]) j++;
}
if (!(a[k]< a[j])) break;
exch(a[k], a[j]); k = j;
}
}
template <class Item>
void heapsort4(Item a[], int l, int r)
{ int k, N = r-l+1;
for (k = (N+1)/4; k >=1; k--)
fixDown4(&a[0], k, N);
while (N > 1)
{
exch(a[1], a[N]);
fixDown(&a[0], 1, --N);
}
}
template <class Item>
void replace_max(Item a[], Item x, int n)
{
a[1] = x;
fixDown(a, 1, n);
}
int main()
{
int m, n, i, a[100000], b[100000], c[100000];
cout << "Enter the size of the Heap: " ;
cin >> m;
for(i=1; i<=m; i++)
{ a[i] = rand();
b[i]= a[i];
c[i]= a[i];
}
heapsort(a, 1, m);
heapsort3(b, 1, m);
heapsort4(c, 1, m);
cout << "Number of comparision: "<<c2 <<" " <<c3<<" "<<c4<<"\n";
system("pause");
}