I have a function bubble_sort_linkedList declared as,
void bubble_sort_linkedList(node *head);
The definition of the function (to sort in ascending order) goes like this :
void bubble_sort_linkedList(node *head){
node *ptr, *lptr;
int temp;
lptr = NULL; ptr = head;
if(ptr == NULL || ptr->next == NULL)
return;
while(ptr != lptr){
while(ptr->next != lptr){
if(ptr->next->value < ptr->value){ // Change the inequality sign
temp = ptr->next->value;
ptr->next->value = ptr->value;
ptr->value = temp;
}
ptr = ptr->next;
}
lptr = ptr;
ptr = head;
}
return;
}
Now, I want the same function to sort in descending order too, with just one change of sign in commented line.
So, the change that I plan to make is :
void bubble_sort_linkedList(node *head, bool is_ascending); //Prototype declaration
is_ascending is the decision passed from the main function.
Same function, but ternary operator used as placeholder (This is the part I am confused about, can ternary operator be used as shown below?)
void bubble_sort_linkedList(node *head, bool is_ascending){
node *ptr, *lptr;
int temp;
lptr = NULL; ptr = head;
if(ptr == NULL || ptr->next == NULL)
return;
while(ptr != lptr){
while(ptr->next != lptr){
if(ptr->next->value ((is_ascending) ? <:>) ptr->value){
temp = ptr->next->value;
ptr->next->value = ptr->value;
ptr->value = temp;
}
ptr = ptr->next;
}
lptr = ptr;
ptr = head;
}
return;
}
You cannot do it this way. But you can write an expression that will do a conditional comparison:
if (is_ascending ? ptr->next->value < ptr->value : ptr->next->value > ptr->value) ...
If is_ascending
is guaranteed to be 0
or 1
, here is an alternative with a single test that may be faster:
if ((ptr->next->value < ptr->value) == is_ascending) ...
Identical elements will be ordered differently, but the sort will still be correct.