Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
sort
d
communitycreator

How to sort an array in ascending and descending order in D

Theodore Kelechukwu Onyejiaku

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
}
Sort the array in ascending order

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
}
Sort the array in descending order

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.

RELATED TAGS

array
sort
d
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.