Python Program to Sort Words in Alphabetic Order

In this example, you will learn how to sort Words in Alphabetic Order.

Lexicographical order is a way of arranging words based on the alphabetical order of their individual letters.

We will use three different Python programs to sort words in alphabetical order using different methods with higher optimization.

The three different methods are as follows.

  • sort Words in Alphabetic Order Using the sorted() function
  • sort Words in Alphabetic Order Using the sort() method of the list
  • sort Words in Alphabetic Order Using the bubble sort algorithm

sort Words in Alphabetic Order Using the sorted() function

Program to sort words in alphabetical order using the sorted() function

string = input("Enter a string: ")

words = string.split()

sorted_words = sorted(words)

print("Sorted words in alphabetical order:", ' '.join(sorted_words))

Output

Enter a string: hello world python
Sorted words in alphabetical order: hello python world

sort Words in Alphabetic Order Using the sort() method

Program to sort words in alphabetical order using the sort() method from Python list datastructure.

string = input("Enter a string: ")

words = string.split()

words.sort()

print("Sorted words in alphabetical order:", ' '.join(words))

Output

Enter a string: python django java spring boot
Sorted words in alphabetical order: boot django java python spring

sort Words in Alphabetic Order Using the bubble sort algorithm

Program to sort words in alphabetical order using bubble sort algorithm

string = input("Enter a string: ")

words = string.split()

n = len(words)

for i in range(n):
    for j in range(0, n-i-1):
        if words[j] > words[j+1]:
            words[j], words[j+1] = words[j+1], words[j]

print("Sorted words in alphabetical order:", ' '.join(words))

Output

Enter a string: django java rust c#
Sorted words in alphabetical order: c# django java rust

Conclusion

In the first two examples, we use a Python built-in function to sort the words in alphabetical order, while the third method implements the bubble sort algorithm to sort the words.

The bubble sort algorithm is not the most efficient algorithm for sorting, but it is relatively simple to implement and can be optimized further.

Leave a Comment