Reputation: 35
I need to sort a list either in ascending or descending order according to the preference order computed by whatever function is passed as its second argument.
Pretty much the algorithm finds the minimum value, swaps it with the value in the first position or the last position depending on the calculation by the function passed as its 2nd argument of sort list( ) function call.
Here is my code I just don't know how to implement a function passing for it to go ascending or descending. Mine only goes one way:
#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;
}
Upvotes: 2
Views: 251
Reputation: 1440
You need to provide comparator functions. You can pass it to sorting function as function pointers, and use them instead of built-in operation.
Like this:
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;
}
}
}
}
Then
sort(&head, less);
or
sort(&head, greater);
Upvotes: 3