Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

programing
functions
d
communitycreator

How to arrange the elements of an array in D

NDUKWE CHIDERA K.

Overview

In D, an array should be declared as any of the basic types. These types make it possible for the array, only to hold a particular data type. This is unlike tuples, which can accept elements of different types.

The sort() function

We can use a built-in method, sort(), to arrange the members of these arrays in different orders.

The default sort order of the sort() function is from the lowest to the highest value, in ascending order. However, we can use the predicate parameter of the function to sort it in descending order.

sort(predicate,array_to_sort)

Parameters

  • predicate: This determines how sort() is carried out.
  • array_to_sort: This is the array whose elements are to be sorted.

Return value

This method sorts an array.

Example

Due to the need to evaluate the predicate condition during evaluation, we used array.sort!(the_predicate) instead. This allows the predicate condition to be evaluated during runtime and it sorts the array.

import std.algorithm;
import std.stdio;

void main(){
    int[] array_sort = [ 7, 4, 9, 2 ];
    
    // sort in descending order
    writeln("Descending order: ",array_sort.sort!("a > b"));
    // sort in ascending order
    writeln("Ascending order: ",sort(array_sort));
    //you can still do this
    writeln(array_sort.sort()); // [2, 4, 7, 9]
    // create custom comparator
    alias myComp = (x, y) => x > y;
    writeln(array_sort.sort!(myComp)); // [9, 7, 4, 2]  
}
Implementation of sort() function

Explanation

  • Line 1–2: We import some modules.
  • Line 4: We start the main wrapper function.
  • Line 5: We declare the array_sort variable.
  • Lines 8–12: We use the sort() method and print its output to the console.
  • Line 14: We create a custom reusable comparator.
  • Line 15: We use the created custom reusable comparator in the sort() method.

RELATED TAGS

programing
functions
d
communitycreator
RELATED COURSES

View all Courses

Keep Exploring