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

标签 c sorting function-pointers

这可能是一个非常基本的问题,但我无法彻底理解指针。在我下面的程序中,在 main 方法中,我只是想知道测试 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,但被视为 char。结果将毫无意义。

关于以比较函数作为参数调用快速排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22827923/

相关文章:

c - 无法从用户空间应用程序访问结构数组

c - 使用冒泡排序对指针数组进行排序,返回未排序的数组

Java 算法 - 与 ArrayList 的合并排序

c++ - 为什么这个函数调用在通过类型转换的函数指针调用它后表现得很好?

swift - 从 Cocoa 中的 C api 调用 Swift 闭包时出现访问错误

c - 与正常函数调用相比仍然没有得到回调

c - 搜索/打印数组中的特定元素

c - 以指数方式更新并打印一个数字

循环计算

algorithm - Python Hadoop 流式处理,二次排序问题