Algorithm
-
Input:
- Accept a list of words as input.
-
Tokenization:
- Tokenize the input string into individual words. You can use a regular expression or the
split
method to achieve this.
- Tokenize the input string into individual words. You can use a regular expression or the
-
Sorting:
- Use the
sort
method to sort the array of words. Thesort
method sorts elements of an array in place and by default, it sorts strings in alphabetical order.
- Use the
-
Output:
- Display or return the sorted list of words.
Code Examples
#1 Code Example- Sort Words in Alphabetical Order
Code -
Javascript Programming
// program to sort words in alphabetical order
// take input
const string = prompt('Enter a sentence: ');
// converting to an array
const words = string.split(' ');
// sort the array elements
words.sort();
// display the sorted words
console.log('The sorted words are:');
for (const element of words) {
console.log(element);
}
Copy The Code &
Try With Live Editor
Output
Enter a sentence: I am learning JavaScript
The sorted words are:
I
JavaScript
am
learning
The sorted words are:
I
JavaScript
am
learning
#2 Code Example with Javascript Programming
Code -
Javascript Programming
// program to sort words in alphabetical order
// take input
const string = prompt('Enter a sentence: ');
// converting to an array
const words = string.split(' ');
// sort the array elements
words.sort();
// display the sorted words
console.log('The sorted words are:');
for (const element of words) {
console.log(element);
}
Copy The Code &
Try With Live Editor
Output
Enter a sentence: i am learning javascript
The sorted words are:
am
i
javascript
learning
The sorted words are:
am
i
javascript
learning
Demonstration
JavaScript Programing Example to Sort Words in Alphabetical Order-DevsEnv