- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 the words in lexicographical order in Java
The words are sorted in lexicographical order or dictionary order. This means that the words are alphabetically ordered based on their component alphabets. An example of this is given as follows.
The original order of the words is Tom Anne Sally John The lexicographical order of the words is Anne John Sally Tom
A program that demonstrates this is given as follows.
Example
public class Example { public static void main(String[] args) { String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" }; int n = 5; System.out.println("The original order of the words is: "); for(int i = 0; i < n; i++) { System.out.println(words[i]); } for(int i = 0; i < n-1; ++i) { for (int j = i + 1; j < n; ++j) { if (words[i].compareTo(words[j]) > 0) { String temp = words[i]; words[i] = words[j]; words[j] = temp; } } } System.out.println("
The lexicographical order of the words is: "); for(int i = 0; i < n; i++) { System.out.println(words[i]); } } }
Output
The original order of the words is: Peach Orange Mango Cherry Apple The lexicographical order of the words is: Apple Cherry Mango Orange Peach
Advertisements