Fill in the blank code - generic Bubble sort - C
Hello everyone.
This is the correct filling of generic bubble sort code.
Some little technical question about the first argument of genSort function -
According to the main, I thought the right type to be passed at first is of ConstElement type, as the main defines an array of 5 ConstElement (which is defining an array of 5 const void pointers).
Now, when we pass at the main the first argument (arrToSort) - we are actually passing the pointer to the first element which is of ConstElement type as I see the things.
But, we see that the correct argument type of genSort function is Element.
What's the problem with my understanding?
Thanks!
Code:
#include <stdio.h>
#include <assert.h>
typedef void* Element;
typedef const void* ConstElement;
void genSort(Element arrToSort, int arrSize, int (*less)(ConstElement, ConstElement))
{
int numOfPasses;
if (arrSize < 2)
return;
for (numOfPasses = 0 ; numOfPasses < arrSize ; ++numOfPasses) {
int it;
for (it = 0 ; it < arrSize - 1 ; ++it) {
if (less(arrToSort[it+1], arrToSort[it]))
{
ConstElement temp = arrToSort[it+1];
arrToSort[it+1] = arrToSort[it];
arrToSort[it] = temp;
}
}
}
}
int IntLess(ConstElement a, ConstElement b) {
int *i1 = (int*) a;
int *i2 = (int*) b;
assert(i1 != NULL && i2 != NULL);
return (*i1 < *i2);
}
int main() {
int A[5] = {5, 6, 2, 23, 9};
int tempi;
ConstElement arrToSort[5];
for (tempi = 0 ; tempi < 5 ; ++tempi)
arrToSort[tempi] = A + tempi;
genSort(arrToSort, 5, &IntLess);
/* will print 2 */
printf("arrToSort[0] = %d\n", *((int *) arrToSort[0]));
return 0;
}