Reputation: 45
This is probably a very basic question, but I'm having trouble with understanding pointers thoroughly. In my program below, in the main method, I'm just wondering what the right way to test my Qsort function is. Thanks in advance!
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j]=temp;
}
int cmp1 (void *first_arg, void *second_arg)
{
int first = *(int *)first_arg;
int second = *(int *)second_arg;
if ( first < second )
{
return -1;
}
else if ( first == second )
{
return 0;
}
else
{
return 1;
}
}
int cmp2 (void * a, void * b)
{
return ( *(int *)a - *(int *)b );
}
void cmp3 (void *a, void *b)
{
char one = *(char *)a;
char two = *(char *)b;
if (one == two){
printf("The two values are equal");
}
else
{
printf("The two values are not equal");
}
}
void QSort(void *v[],int left, int right, int (*compare)(void *first, void *second))
{
int i, last;
void swap (void *v[],int ,int);
if(left >= right){
return;
}
swap(v,left,(left+right)/2);
last=left;
for(i=left+1;i<=right; i++){
if((*compare)(v[i],v[left])<0){
swap(v,++last,i);
}
}
swap(v,left,last);
QSort(v,left,last-1,compare);
QSort(v,last+1,right,compare);
}
int main()
{
int first = 23;
int second = 4;
int third = 5;
int temp[3];//={22,4,36,64,0};
temp[0] = (void *)&first;
temp[1]=(void *)&second;
temp[2]=(void *)&third;
QSort(temp, 0, 2, cmp1(.....));
for(int n=0;n<3;n++){
printf("%d ",*((int *)temp[n]));
}
return 0;
}
Upvotes: 1
Views: 894
Reputation: 665
temp is not an integer array, it should be array of integer pointers.
line
int temp[3];
should be replaced with
int *temp[3];
Upvotes: 0
Reputation: 15121
QSort(temp, 0, 2, cmp1(.....));
shoud be
QSort(temp, 0, 2, cmp1);
If foo
is name of a function, then you use foo()
to call it, and use foo
to pass it as an argument to another function that requires a function pointer.
Upvotes: 1
Reputation: 64308
cmp1
is really the best way. It should always perform correctly.
cmp2
is close. It would work most of the time, but if you are dealing with very large integers, the results would be wrong.
cmp3
is definitely not right. The values are actually int
s, but are being treated as char
s. The results would be meaningless.
Upvotes: 2