
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Elements in Lexicographical Order in Swift
This tutorial will discuss how to write a Swift program to sort elements in lexicographical order(Dictionary order).
An arrangement of the words, characters or numbers in alphabetical order staring from A to Z is known as lexicographic order. It is also known as dictionary order because the searching of the words are same as we search in the real dictionary. In lexicographical order, the words whose first letter is same are arranged in the same group and in the group words are sorted according to their second letter and so on.
To sort the given list of elements into lexicographic order Swift provide a built-in function named sort(). This function is used to sort the elements of the array in lexicographic order.
You can sort the elements either in ascending or deceasing order. By default this function sorts the elements in ascending order.
Syntax
Following is the syntax of the function ?
arrayVar.sort()
Below is a demonstration of the same ?
Input
Suppose our given input is ?
List of words are - ["Apple", "Apricot", "Avocado", "Amla"]
Output
The desired output would be ?
Amla, Apple, Apricot, Avocado
Algorithm
Following is the algorithm ?
Step 1 ? Declare an array variable with values.
Step 2 ? Print the original array using for loop.
Step 3 ? Sort the elements of the array in lexicographical order(Dictionary order) using sort() function.
myWords.sort()
Step 4 ? Print the output.
Example
The following program shows how to sort elements in lexicographical order(Dictionary order).
import Foundation import Glibc var myWords = ["Apple", "Apricot", "Kiwi", "Banana", "Mango", "Avocado", "Beetroot", "Amla"] print("Original List:") for i in myWords{ print(i) } // Sorting elements in lexicographical order myWords.sort() print("\nSorted List(lexicographical order):") for j in myWords{ print(j) }
Output
Original List: Apple Apricot Kiwi Banana Mango Avocado Beetroot Amla Sorted List(lexicographical order): Amla Apple Apricot Avocado Banana Beetroot Kiwi Mango
Here, in the above code, we have an array named myWords with value now we change the order of the array in lexicographic order using sort() function and display the output.