Swift Program to Sort the Elements of an Array in Descending Order


In this article, we will learn how to write a swift program to sort the elements of an array in descending order. To sort the elements of an array Swift provides an in-built function named sort(by:). This function takes one argument and then sorts the array according to the condition passed in the by parameter. So to sort the array in descending order we pass > in the by the parameter of the sort(by:) function.

Syntax

func sort(by:)

Here sort(by:) is an instance method. Which will sort the given sequence according to the value of by: parameter. Here if you want to sort an array in descending order then pass the > operator Or if you want to sort an array in ascending order then pass < operator as a parameter.

Algorithm

  • Step 1 − Create an array.

  • Step 2 − Sort the array in descending order using the sort(by:) method 

Array1.sort(by:>)
  • Step 3 − Print the output

Example

In the following example, we pass > in the by the parameter of the sort(by:) function to sort the given arrays into descending order. This function can sort an array of any data type.

import Foundation
import Glibc
 
// Creating arrays
var Array1 : [String] = ["bus", "car", "bicycle", "bike"]
var Array2 : [Int] = [23, 56, 7, 5, 84, 2]
var Array3 : [Float] = [3.4, 67.3, 1.2, 5.6, 78.3]

// Sorting the array in descending order
// Using sort(by:) method
print("Before Sorting Array 1 is:", Array1)
Array1.sort(by:>)
print("After Sorting Array 1 is", Array1)

print("\nBefore Sorting Array 2 is:", Array2)
Array2.sort(by:>)
print("After Sorting Array 2 is", Array2)

print("\nBefore Sorting Array 3 is:", Array3)
Array3.sort(by:>)
print("After Sorting Array 3 is", Array3)

Output

Before Sorting Array 1 is: ["bus", "car", "bicycle", "bike"]
After Sorting Array 1 is ["car", "bus", "bike", "bicycle"]

Before Sorting Array 2 is: [23, 56, 7, 5, 84, 2]
After Sorting Array 2 is [84, 56, 23, 7, 5, 2]

Before Sorting Array 3 is: [3.4, 67.3, 1.2, 5.6, 78.3]
After Sorting Array 3 is [78.3, 67.3, 5.6, 3.4, 1.2]

Here in the above code, we create there different types of arrays(Int, Float, String). Now we pass > in the by parameter of sort(by:>) method to sort the given array in descending order(high to low).

Conclusion

So by passing the> operator in the sort(by:) method we can sort all the elements of any type of array in descending order. So this is how we can sort the elements of an array in descending order.

Updated on: 20-Dec-2022

526 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements