The topNCopy()
method is an inbuilt method in the D language. The method helps sort
the values of a variable and copy these to the indicated variable. We can choose the size of the sorted variable we want to copy. We determine the size of the array we wish to copy into to have the desired size.
TRange topNCopy(predicate, range1, range2, SortOutput)
predicate
: This optional parameter indicates the sort order. The default sort order is descending.
range1
: This is the variable whose values are to be sorted.
range2
: This is the value into which you want to copy.
SortOutput
: This is a boolean where Yes.sortOutput
means the output to be copied should be sorted in ascending order, and No.sortOutput
indicates a sort in the descending order.
import std.algorithm;import std.stdio;import std.typecons : No, Yes;void main(){int[] y = [ 10, 16, 2, 3, 1, 5, 0 ];int[] z = new int[4];topNCopy(y, z, No.sortOutput);writeln(z); // [3, 1, 2, 0]topNCopy(y, z, Yes.sortOutput);writeln(z); // [0, 1, 2, 3]}
Line 1,2, and 3: We import some modules.
Line 5: Start the main function.
Line 7: Declare the array y
.
Line 8: Declare the array z
, using the new
keyword so that at every point in time the z
variable is called, it will create a new array.
Line 9 and 11: Use the topNCopy()
function.
Line 10 and 12: Print different instances of the variable z
.