I am trying to sort a Dynamic Array list but it just doesn't work and I don't understand how I should do it. This is what I've done so far:
void ascending_sort(Controller* ctrl)
{
int i,j;
Cost* aux;
DynamicVector* c=getAllCosts(ctrl);
for(i=0;i<getLen(c)-1;i++)
{
Cost* cost;
for(j=i+1;j<getLen(c);j++)
{
if(cost[i].sum < cost[j].sum)
{
aux=cost[i]; //error
cost[i]=cost[j];
cost[j]=aux; //error
}
}
}
}
Here's the struct:
typedef struct{
char* day;
char* type;
int sum;
}Cost;
How can I fix it? I think I am doing something wrong when I declare "Cost* aux". I hope you can help me!
EDIT: I updated the new code for the sorting function. Now it doesn't print what I want. It prints 'Cost 1' and nothing else and then I receive an "End program" window that stops everything. What could be the problem?
This is the new sorting algorithm:
void ascending_sort(Controller* ctrl)
{
int i,j;
DynamicVector* c=getAllCosts(ctrl);
for(i=0;i<getLen(c)-1;i++)
{
Cost* cost=getElementAtPosition(c,i); //returns element on position
for(j=i+1;j<getLen(c);j++)
{
if(cost[i].sum < cost[j].sum)
{
const Cost aux=cost[i];
cost[i]=cost[j];
cost[j]=aux;
}
}
}
}
This is the print function: //this function is in the console
void PrintCosts(Console* console)
{
DynamicVector* CostList=getAllCosts(console->ctrl);
if (getLen(CostList))
{
int i;
for(i=0;i<getLen(CostList);i++)
{
printf("\nCost %d\n\n",i+1);
Cost *c=(Cost*)getElementAtPosition(CostList,i);
PrintCost(c);
}
}
else printf("No cost in the list!");
}
and this is the function that calls the sort function from controller to console:
void AscendingSort(Console* console)
{
ascending_sort(console->ctrl);
}