在C中使用快速排序以反向排序(降序)? [英] Using Quick Sort in C to sort in reverse direction (descending)?

查看:230
本文介绍了在C中使用快速排序以反向排序(降序)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

排序方式为qsort(myArray,100,sizeof(int), comp)

int comp(const int * a, const int * b)
if(a==b)
{
    return 0;
}
else
{
    if(a<b)
    {
        return -1;
    }
    else
    {
        return 1;
    }
}

首先, 当我对数组(9,8,7,6,5,4,3,2,1,1),排序时,我得到的是(4,8,7,6,5,9,3,2,1)-并不是真正的排序,这实际上是行不通的.

First, This doesn't really work, when I sort an array (9,8,7,6,5,4,3,2,1,1), I get (4,8,7,6,5,9,3,2,1) - NOT really sorted.

第二, 我将如何向另一个方向排序?我需要通过的qsort是否有特殊标志?

Second, How would I sort in the other direction? Is there a special flag for qsort I need to pass?

推荐答案

更改比较功能,以便按自己喜欢的方式进行排序.

Change your compare function so that it is ordering the way you like.

并且compare函数采用指向比较数据的指针(而不是数据本身).例如

And the compare function takes pointers to compared data (not the data itself). Eg.

int compare (const void* p1, const void* p2)
{ 
   int i1 = *(int*) p1;
   int i2 = *(int*) p2;
   if (i1 < i2) return -1;
   else if (i1 == i2) return 0;
   else return 1;
   /* or simply: return i1 - i2; */
 }

这篇关于在C中使用快速排序以反向排序(降序)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆