Algorithm
-
Input:
- Take a sentence as input.
Processing:
1. Split the input sentence into a list of words.
2. Sort the list of words in alphabetic order using the sorted() function.
3. Join the sorted words back into a sentence.
Output:
- Display or return the sorted sentence.
Code Examples
#1 Code Example- Python Program to Sort Words in Alphabetical Order
Code -
Python Programming
def sort_words(words):
sorted_words = sorted(words)
return sorted_words
# Example usage
word_list = ['banana', 'apple', 'cherry', 'date', 'elderberry']
sorted_words = sort_words(word_list)
print(sorted_words)
Copy The Code &
Try With Live Editor
Output
#2 Code Example- Sort Words in Alphabetical Order Without Sort Function
Code -
Python Programming
def sort_words(words):
n = len(words)
for i in range(n - 1):
for j in range(n - i - 1):
if words[j] > words[j + 1]:
words[j], words[j + 1] = words[j + 1], words[j]
return words
# Example usage
word_list = ['banana', 'apple', 'cherry', 'date', 'elderberry']
sorted_words = sort_words(word_list)
print(sorted_words)
Copy The Code &
Try With Live Editor
Output
Demonstration
Python Programing Example to Sort Words in Alphabetic Order-DevsEnv