How to sort an array in ascending and descending order in D
Overview
We use the sort() method in D to sort an array in an ascending or descending order.
Syntax
We use the syntax below to sort in ascending order:
array.sort()
We use the syntax below to sort in descending order:
array.sort!("a > b");
Parameters
This method takes no parameters.
Return value
The method returns the array with sorted values according to the specified order.
Code example: Ascending
// import librariesimport std.stdio;import std.algorithm;// main methodvoid main(string[] args) {int[] array = [50, 20, 10, 45, 34]; // create arrayarray.sort(); // sort the arraywriteln(array); // print array elements}
Explanation
- Line 8: We create an array.
- Line 9: We sort the array in ascending order using the
sort()method. - Line 10: We print the sorted array.
Code example: Descending
// import librariesimport std.stdio;import std.algorithm;// main methodvoid main(string[] args) {int[] array = [50, 20, 10, 45, 34]; // create arrayarray.sort!("a > b"); // sort the arraywriteln(array); // print array elements}
Explanation
- Line 8: We create an array.
- Line 9: We sort the array in descending order using the
sort("a > b")method. - Line 10: We print the sorted array.