I am following the provided sorting algorithm:
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?
CodePudding user response:
Code is errantly doing a do {} while
when a while {}
is needed.
Consider if the array was initially sorted. The first (*A)[i 1] = (*A)[i];
messes up the array.
CodePudding user response:
Arrays in C start with index 0 and elements are stored in positions 0 to n-1
for (int j = 1; j < size; j ){
You changed "while {}" which check before loop to "{} while", which check after loop, moving element without comparison.
while(i >= 0 && (*A)[i] > key) {
(*A)[i 1] = (*A)[i];
i--;
};