c - Usage of ternary operator as placeholder -
i have function bubble_sort_linkedlist declared as,
void bubble_sort_linkedlist(node *head);
the definition of function (to sort in ascending order) goes :
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 inequality sign temp = ptr->next->value; ptr->next->value = ptr->value; ptr->value = temp; } ptr = ptr->next; } lptr = ptr; ptr = head; } return; }
now, want same function sort in descending order too, 1 change of sign in commented line.
so, change plan make :
void bubble_sort_linkedlist(node *head, bool is_ascending); //prototype declaration
is_ascending decision passed main function.
same function, ternary operator used placeholder (this part confused about, can ternary operator used 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 way. can write expression conditional comparison:
if (is_ascending ? ptr->next->value < ptr->value : ptr->next->value > ptr->value) ...
if is_ascending
guaranteed 0
or 1
, here alternative single test may faster:
if ((ptr->next->value < ptr->value) == is_ascending) ...
identical elements ordered differently, sort still correct.
Comments
Post a Comment