Introduction
In this tutorial, you will learn How to sort a string in Python without using any built-in function (sort or sorted method).
To solve this problem I will use here the Quick Sort method. If you are not familiar with this sorting technique, please see another post on Quick Sort in Python.
I hope you got the touch of this sorting technique. Now we can jump into the code directly.
Visit Also: URLify a Given String in Python - Replace Spaces by %20
What is sort() and sorted() method?
Both sort() and sorted() are built-in methods of Python. Both are used to sort list items (there are slight differences between these two methods). By default it sorts the items in ascending order but reverse order is also possible by specifying the reverse order true.
The Code
First, we'll iterate through each character in the string and store it in a Python List, except for the SPACE character. The rest of the code is similar to the traditional method of the Quick Sort technique.
'''Sorting a String in Python without using sort function'''
def partition(array, low, high):
pivot = array[high]
index = low - 1
for j in range(low, high):
if array[j] < pivot:
index += 1
array[index], array[j] = array[j], array[index]
array[index + 1], array[high] = array[high], array[index + 1]
return index + 1
# quickSort Function
def quickSort(array, low, high):
if low < high:
mid = partition(array,low,high)
quickSort(array, low, mid - 1)
quickSort(array, mid+1, high)
# The main Function
if __name__ == "__main__":
# Enter your text here
text = "Hello World"
# pre-declared list
text_list = []
# Adding each character of the
# string to the list (except 'SPACE')
for char in text:
if char == " ":
pass
else:
text_list.append(char)
# Calling the quickSort Function
quickSort(text_list, 0, len(text_list)-1)
print("The sorted array is: ")
for i in text_list:
print(i, end=' ')
print("\n")
Output
The sorted String is:
HWdellloor
Note
You can take string input from the user at runtime instead of declaring it at compile time.