c - 按升序和降序对列表进行排序

标签 c algorithm sorting

我需要根据作为第二个参数传递的任何函数计算出的优先顺序,以升序或降序对列表进行排序。

该算法几乎找到最小值,将其与第一个位置或最后一个位置的值交换,具体取决于作为 sort list( ) 函数调用的第二个参数传递的函数的计算。

这是我的代码,我只是不知道如何实现传递它以升序或降序传递的函数。我的只有一种方式:

#include <stdio.h>
#include <stdlib.h>

typedef struct iorb {
int base_pri;
struct iorb *link;
char filler[100];
} IORB;

int push(struct iorb **h, int x)
{
struct iorb *temp = (struct iorb*)malloc(sizeof(struct iorb));
temp->base_pri = x;
temp->link = *h;
*h = temp;
return 0;
}

void print(struct iorb *head)
{
struct iorb *temp = head;
while(temp != NULL)
{
    printf("%d ",temp->base_pri);
    temp = temp->link;
}
printf("\n");
}

void sort(struct iorb **h)
{
int a;

struct iorb *temp1;
struct iorb *temp2;

for(temp1=*h;temp1!=NULL;temp1=temp1->link)
  {
    for(temp2=temp1->link;temp2!=NULL;temp2=temp2->link)
      { 
        if(temp2->base_pri < temp1->base_pri)
          {
            a = temp1->base_pri;
            temp1->base_pri = temp2->base_pri;
            temp2->base_pri = a;
          }
       }
   }
}

int main()
{
struct iorb * head = NULL;
push(&head,5);
push(&head,4);
push(&head,6);
push(&head,2);
push(&head,9);
printf("List is : ");
print(head);
sort(&head);
printf("after sorting list is : ");
print(head);
return 0;
}

最佳答案

您需要提供比较器功能。您可以将其作为函数指针传递给排序函数,并使用它们代替内置操作。

像这样:

int less(int lh, int rh)
{
    return lh < rh;
}

int greater(int lh, int rh)
{
    return !less(lh, rh);
}

void sort(struct iorb **h, bool (*comp)(int, int))
{
int a;

struct iorb *temp1;
struct iorb *temp2;

for(temp1=*h;temp1!=NULL;temp1=temp1->link)
  {
    for(temp2=temp1->link;temp2!=NULL;temp2=temp2->link)
      { 
        if(comp(temp2->base_pri, temp1->base_pri))  // Using a comparator.
          {
            a = temp1->base_pri;
            temp1->base_pri = temp2->base_pri;
            temp2->base_pri = a;
          }
       }
   }
}

然后

sort(&head, less);

sort(&head, greater);

关于c - 按升序和降序对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50252557/

相关文章:

c - 如何在 Eclipse 中编写不同的 C 小程序,所有这些程序都有自己的 main()?

c++ - 为什么我的合并排序代码比插入排序慢

c - 将数据从struct读取到二维数组c中

c - 赋值中的类型不兼容,为什么我不能这样做?

C : how can I change from file descriptor to FILE struct and vice versa?

php - 如何使用 PHP 读取 csv 文件中的第二列?

algorithm - 浅析凸包的格雷厄姆扫描算法

c++ - 在集合中查找重复元素并将其分组的快速算法是什么?

javascript - 判断字符串中的所有字母是否按字母顺序排列 JavaScript

python - 对 NumPy 数组进行排序并同时排列另一个数组