I am following the provided sorting algorithm:
INSERTION-SORT(A)
1 for j <- 2 to length[A]
2 do key <-A[j]
3 Insert A[j] into the sorted sequence A[1..j — 1].
4 i <- j — 1
5 while i > 0 and A[i] > key
6 do A[i + 1] <- A[i]
7 i <- i — 1
8 A[i + 1] <— key
Provided by Introduction to Algorithms by Cormen, I have attempted with the following:
#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 6
void sorting(int (*A)[MAXSIZE]){
int key;
int i;
size_t size = sizeof(*A)/sizeof((*A)[0]);
for (int j = 1; j < size; j++){
key = (*A)[j];
i = j-1;
do {
(*A)[i+1] = (*A)[i];
i--;
}while(i > 0 && (*A)[i] > key);
(*A)[i+1] = key;
}
for(int k = 0; k < size; k++){
printf("\n%d", (*A)[k]);
}
}
int main(void){
int B[MAXSIZE] = {5, 2, 4, 6, 1, 3};
int result;
sorting(&B);
return 0;
}
However, the output is not sorting correctly. Did I miss something with these steps?
do { ... } while (...)instead of pre-condition loop used in the pseudocode.do { X } while (Y);means "do X while Y is held", and Y is checked after each iteration. In particular, at least one iteration is executed.while (Y) {X}means "while Y, do X", and Y is checked before each iteration. In particular, it's possible to have zero iterations.Aasint (*A)[MAXSIZE]?