Find distinct elements and other operations on the arrays.
The union of two arrays
The union operation combines two sets, skipping the matching values of both sets while populating the resultant set.
Unlike sets, arrays may contain duplicate values. For example:
-
The union of and should be .
-
The union of and should be .
-
The union of and should be .
The following program unites two arrays, assuming that the operand arrays are sorted. This operation may result in duplicate values.
In the code above:
-
The first loop traverses through both arrays (
p
andq
) and puts the smaller value in the resultingr
array. After completing this round, any one array is exhausted. -
The other array still has one or more untraversed values, all of which are certainly greater than or equal to the last value of the exhausted array.
-
Therefore, one of the next two loops executes to add those values to the end of
r
without comparison.
The intersection of two arrays
The intersection operation gives the matching values of two arrays. Unlike sets, arrays may contain duplicate values. For example:
-
The intersection of and should be .
-
The intersection of and should be .
-
The intersection of and should be .
The following program assumes that the operand arrays are sorted, and may result in duplicate values:
Note: If the operand arrays are not sorted already, then the code for sorting them should be added before entering the first loop.
The minus operator for two arrays
The following program implements the minus operator for arrays similar to sets. It’s assumed that the operand arrays are sorted, and the resulting array may contain duplicates, depending on the contents of the operands.
Distinct values in an array
The following program generates a new array with the unique values of the operand array:
Note: If the operand array is not sorted already, then the code to sort it should be added before entering the loop.
Get hands-on with 1400+ tech skills courses.