Python Program to Sort a String
Sorting has always been quite a popular utility with lots of applications everywhere, where Python language opts. Python in its language offers a sort function to perform this task. But because not all the Python containers are mutable, such as string, the sort function doesn’t work as it is in place trying to sort and immutability stops this. Let’s discuss specific ways in which a string can be sorted.
Example
Input: geekforgeeks
Output: eeeefggkkors
Explaination:The Sorting the characters in ascending order gives us "eeeefggkkors".
Program to Sort a String in Python
Below are the lists of methods that we will cover:
Program to sort a string using join() and sorted()
The combination of the above functions can potentially solve this particular problem. This task is performed in 2nd step in which the first step we get the sorted list of characters and then we join the result to get the resultant sorted string.
Python3
test_string = "geekforgeeks"
print ( "The original string : " + str (test_string))
res = ''.join( sorted (test_string))
print ( "String after sorting : " + str (res))
|
Output
The original string : geekforgeeks
String after sorting : eeeefggkkors
Time Complexity: The time complexity of the code is O(n log n).
Space Complexity: The space complexity of the given code is O(n).
Sort a Python String using the Native Method
To sort a given string with user input using the inbuilt Python sort method.
Python3
String = "geekforgeeks"
print ( 'Original String: ' , String)
lst = list (String)
lst.sort()
print ( 'Sorted String: ' )
for i in lst:
print (i, end = "")
|
Output:
Original String: geekforgeeks
Sorted String:
eeeefggkkors
Time Complexity: The time complexity of the code is O(n log n).
Space Complexity: The space complexity of the given code is O(n).
Sort a Python String using reduce() and lambda
This particular task can also be performed using a combination of the above functions. Here we join the resultant sorted list of characters using the lambda function joined by the reduce function. Works only for Python2
Python
test_string = "geekforgeeks"
print ( "The original string : " + str (test_string))
res = reduce ( lambda x, y: x + y, sorted (test_string))
print ( "String after sorting : " + str (res))
|
Output
The original string : geekforgeeks
String after sorting : eeeefggkkors
Time Complexity: The time complexity of the code is O(n log n).
Space Complexity: The space complexity of the given code is O(n).
Sort a string in Python using Bubble Sort
Convert the string into a list of characters then use the bubble sort algorithm to sort the list now join the sorted list to form a string.
Python3
def sort_string(s):
chars = list (s)
n = len (chars)
for i in range (n):
for j in range ( 0 , n - i - 1 ):
if chars[j] > chars[j + 1 ]:
chars[j], chars[j + 1 ] = chars[j + 1 ], chars[j]
return ''.join(chars)
s = "geekforgeeks"
print ( "Original string:" , s)
print ( "String after sorting:" , sort_string(s))
|
Output
Original string: geekforgeeks
String after sorting: eeeefggkkors
Time complexity: O(n^2) because we use the bubble sort algorithm which has a time complexity of O(n^2).
Auxiliary Space: O(n) because we create a new list of characters from the original string.
Program to sort a string using the Merge Sort
This approach uses the merge sort algorithm to sort the characters in the string. It first converts the string into a list of characters, and then recursively divides the list in half until the base case of a single element is reached. The two halves are then merged back together in sorted order using the merge() function. The sorted list is then converted back into a string.
Python3
def merge_sort(s):
if len (s) < = 1 :
return s
mid = len (s) / / 2
left = merge_sort(s[:mid])
right = merge_sort(s[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len (left) and j < len (right):
if left[i] < right[j]:
result.append(left[i])
i + = 1
else :
result.append(right[j])
j + = 1
result + = left[i:]
result + = right[j:]
return result
s = 'geekforgeeks'
sorted_s = ''.join(merge_sort( list (s)))
print ( "String after sorting:" , sorted_s)
|
Output
String after sorting: eeeefggkkors
Time Complexity: O(n log n) where n is the length of the input string “s”.
Space Complexity: O(n) where n is the length of the input string “s”.
Sort a String in a Python Program using a Dictionary
This program sorts a given input string in ascending order based on the characters present in it. It uses a dictionary to count the frequency of each character and then sorts them based on the ASCII value of the character.
Python3
input_string = "geekforgeeks"
char_count = {}
for char in input_string:
if char in char_count:
char_count[char] + = 1
else :
char_count[char] = 1
sorted_string = ""
for char in sorted (char_count.keys()):
sorted_string + = char * char_count[char]
print ( "Original string: {}" . format (input_string))
print ( "String after sorting: {}" . format (sorted_string))
|
Output
Original string: geekforgeeks
String after sorting: eeeefggkkors
Time Complexity: The time complexity of this algorithm is O(nlogn) due to the use of the sorted() function.
Space Complexity: The space complexity of this algorithm is O(n) due to the use of the dictionary to store the count of each character.
Last Updated :
04 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...