Help me with Pyramidal sorting by D. Knuth algorithm in C++.
I would like to clarify if I followed the algorithm correctly.
The code works.
I have the function, but I'm not sure if my code fully matches the algorithm's textual description and diagram.
I have a Knuth algorithm in text form:
Records R1,...,RN, N≥2 are rearranged in place; after sorting is complete, their keys will be in order, K1≤...≤KN.
and Nassi-Shneiderman diagram:
Tell me if the code is close to implementing the Knuth algorithm or/and the Nassi-Shneiderman diagram (it's my teacher's diagram)?
My code:
void sortH(int* arK, int N) {
// H1:
int I = N / 2 + 1;
int r = N - 1; // r = N
int K;
// H2:
while (I > 0) {
I = I - 1;
K = arK[I]; // R = arK[l], K = arK[l]
while (true) {
// H3:
int l = I;
int j = 2 * I + 1;
// H4:
while (j <= r) {
// H5:
if (j < r && arK[j] < arK[j + 1]) {
j = j + 1;
}
if (K < arK[j]) {
arK[l] = arK[j];
}
else {
break;
}
l = j;
j = 2 * l + 1;
}
arK[l] = K; // R[i] = R
break;
}
}
// H4:
while (r > 0) {
// H7:
K = arK[r];
arK[r] = arK[0];
r = r - 1;
if (r == 0) {
arK[0] = K;
break;
}
int l = 0, j = 1;
// H5:
while (j <= r) {
if (j < r && arK[j] < arK[j + 1]) {
j = j + 1;
}
// H6:
if (K < arK[j]) {
arK[l] = arK[j];
}
else
{
break;
}
l = j;
j = 2 * l + 1;
}
// H8:
arK[l] = K;
}
}

