C - 调用以比较函数作为参数的快速排序函数


这可能是

一个非常基本的问题,但我在彻底理解指针方面遇到了麻烦。在下面的程序中,在主方法中,我只是想知道测试我的 Qsort 函数的正确方法是什么。提前感谢!

#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;
}

cmp1确实是最好的方法。 它应始终正确执行。

cmp2很近。 它在大多数情况下都有效,但是如果您正在处理非常大的整数,则结果将是错误的。

cmp3绝对是不对的。 这些值实际上是 int s,但被视为 char s。 结果将毫无意义。

QSort(temp, 0, 2, cmp1(.....));

应该成为

QSort(temp, 0, 2, cmp1);

如果foo是函数的名称,则使用 foo() 调用它,并使用 foo 将其作为参数传递给另一个需要函数指针的函数。

temp 不是一个整数数组,它应该是整数指针数组。

线

   int temp[3]; 

应替换为

   int *temp[3];

最新更新