I wanted to brush up on my knowledge of algorithms and I've been using the following book: Algorithms in a nutshell
At page 65 they print an algorithm for insertion sort. The algorithm is pretty simple and straightforward to understand. My issue comes from the way they implemented it. I work mostly in managed languages (C#/Java) so my pointer kung fu is kinda rusty. Here is the code sample they provide:
void sortPointers(void **ar, int n, int(*cmp)(const void *, const void *)) {
int j;
for(j = 1; j < n; j++) {
int i = j - 1;
void* value = ar[j];
while(i >= 0 && cmp(ar[i], value) > 0) {
ar[i+1] = ar[i];
i--;
}
ar[i+1] = value;
}
}
Here is what I added to have a working example:
int cmp(const void* t1, const void* t2) {
if(t1 > t2) {
return 1;
}
else if(t2 > t1) {
return -1;
}
else {
return 0;
}
}
void main() {
int values[] = { 51, 3, 5, 60, 9, 2, 7};
sortPointers((void**)values, 7, cmp);
for(int i = 0; i < 7; i++) {
cout << values[i] << " ";
}
}
While this works I do not completely understand why and how? Also, why does the (void **) cast in the main function work, why did they use a double pointer indirection etc.?
Back in school the only place we used multiple indirection was when dynamically allocating multidimensional arrays. The only other use I know of, is when you need to be able to modify the address the pointer you are passing to the method holds.
Furthermore I went ahead and modified the code to look like this and it works just fine:
void sortPointers2(int* arr, int n, int (*cmp)(int, int)) {
int j;
for(j = 1; j < n; j++) {
int i = j - 1;
int value = arr[j];
while(i >= 0 && cmp(arr[i], value) > 0) {
arr[i+1] = arr[i];
i--;
}
arr[i+1] = value;
}
}
int cmp2(int t1, int t2) {
if(t1 > t2) {
return 1;
}
else if(t2 > t1) {
return -1;
}
else {
return 0;
}
}
void main() {
int values[] = { 51, 3, 5, 60, 9, 2, 7};
sortPointers2(values, 7, cmp2);
for(int i = 0; i < 7; i++) {
cout << values[i] << " ";
}
}
I'm pretty sure I am missing something fundamental and obvious. Thank you for anybody reading this and chipping in with an idea or two. Let me know if you need any additional details or if I messed up the terminology.
EDIT: fixed typo in the first cmp function