This C snippet is part of a merge algorithm implementation:
out[i++] = (in1[i1] < in2[i2]) ? in1[i1++] : in2[i2++];
Can someone please explain how it works?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The code
The code uses what is called the post-increment operator and the ternary/conditional operator (see appendix for more details).
A more verbose version may look something like this:
The algorithm
If the elements in
in1andin2are in sorted order, then the snippet serves as the main part of a merge algorithm to merge the two sorted input buffers into one sorted output buffer.Care must be taken to ensure that
i1andi2are in-bound forin1andin2respectively before comparingin1[i1]againstin2[i2]. Thenin1[i1]is the next available smallest element inin1, and similarlyin2[i2]is the next available smallest element inin2.Without loss of generality, let’s assume
in1[i1] < in2[i2](the other case is a near mirror scenario). Then the next smallest element fromin1is smaller than the next smallest element fromin2, and within1[i1++]on the right hand side of the assignment, we fetch the next smallest value fromin1and advance its pointer to the next available value (if any). Without[i++]on the left hand side of the assignment, we assign the fetched value to a slot in the output buffer and advance its pointer to the next available slot (if any).A higher-level pseudocode of the overall merge algorithm, using a
Queue-like abstract data structure instead of arrays with corresponding pointer indices (for clarity!), may look something like this:See also
Appendex A: Ternary/conditional operator
Essentially, an expression such as this:
first evaluates
condition, and if it’strue, it evaluatestrueExprwhose value becomes the value of the entire expression. If insteadconditionisfalse, the operator instead evaluatesfalseExpr, whose value becomes the value of the entire expression.Related questions
Appendix B: post-increment operator
An expression such as
i++uses what is called a post-increment operator. The operator incrementsi, but the value of this expression is the value ofibefore the increment. By contrast, the value of a pre-increment expression (e.g.++i) is the value ofiafter the increment.There are also pre-decrement (e.g.
--i) and post-decrement as well (e.g.i--).Related questions
On pitfalls like
i = i++;(most of these is Java, but applicable to other languages as well):