首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用比较函数作为参数调用快速排序函数

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

Stack Overflow用户
提问于 2014-04-03 04:33:22
回答 3查看 866关注 0票数 1

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

代码语言:javascript
运行
复制
#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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-04-03 04:39:45

cmp1确实是最好的方法。它应该总是正确的执行。

cmp2接近了。它大部分时间都能工作,但是如果你处理的是非常大的整数,结果将是错误的。

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

票数 2
EN

Stack Overflow用户

发布于 2014-04-03 04:40:16

代码语言:javascript
运行
复制
QSort(temp, 0, 2, cmp1(.....));

应该是

代码语言:javascript
运行
复制
QSort(temp, 0, 2, cmp1);

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

票数 1
EN

Stack Overflow用户

发布于 2014-04-03 04:56:35

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

线路

代码语言:javascript
运行
复制
   int temp[3]; 

应改为

代码语言:javascript
运行
复制
   int *temp[3];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22827923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档