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 libraries
import std.stdio;
import std.algorithm;
// main method
void main(string[] args) {
int[] array = [50, 20, 10, 45, 34]; // create array
array.sort(); // sort the array
writeln(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 libraries
import std.stdio;
import std.algorithm;
// main method
void main(string[] args) {
int[] array = [50, 20, 10, 45, 34]; // create array
array.sort!("a > b"); // sort the array
writeln(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.

Free Resources