Sort the string as per the ASCII values of the characters

ASCII (American Standard Code for Information Interchange) assigns unique numeric values to characters. In Python, we can sort strings based on these ASCII values to arrange characters in ascending order.

Problem Statement

Given a string, we need to sort its characters according to their ASCII values in increasing order. Let's understand this with examples ?

Example 1

Input: "$%7wjk()"

Output: "$%()7jkw"

The ASCII values are ?

$ ? 36
% ? 37
( ? 40
) ? 41
7 ? 55
j ? 106
k ? 107
w ? 119

Example 2

Input: "#m 0f)nk"

Output: " #)0fkmn"

The ASCII values are ?

(space) ? 32
# ? 35
) ? 41
0 ? 48
f ? 102
k ? 107
m ? 109
n ? 110

Using Built-in sorted() Function

Python's sorted() function naturally sorts characters by ASCII values ?

def sort_by_ascii(s):
    return ''.join(sorted(s))

# Test with examples
text1 = "$%7wjk()"
result1 = sort_by_ascii(text1)
print(f"Input: {text1}")
print(f"Output: {result1}")

text2 = "#m 0f)nk"
result2 = sort_by_ascii(text2)
print(f"Input: {text2}")
print(f"Output: {result2}")
Input: $%7wjk()
Output: $%()7jkw
Input: #m 0f)nk
Output:  #)0fkmn

Using Frequency Array Approach

This method uses a frequency array to count character occurrences, then rebuilds the string ?

def sort_by_frequency_array(s):
    # Create frequency array for all ASCII characters (0-127)
    frequency = [0] * 128
    
    # Count frequency of each character
    for char in s:
        frequency[ord(char)] += 1
    
    # Build result string
    result = ""
    for i in range(128):
        if frequency[i] > 0:
            result += chr(i) * frequency[i]
    
    return result

# Test the function
text = "$%7wjk()"
result = sort_by_frequency_array(text)
print(f"Input: {text}")
print(f"Output: {result}")

# Show ASCII values for verification
print("\nASCII values:")
for char in text:
    print(f"'{char}' ? {ord(char)}")
Input: $%7wjk()
Output: $%()7jkw

ASCII values:
'$' ? 36
'%' ? 37
'7' ? 55
'w' ? 119
'j' ? 106
'k' ? 107
'(' ? 40
')' ? 41

Using Custom Key Function

We can explicitly use ord() as the sorting key ?

def sort_with_ord_key(s):
    return ''.join(sorted(s, key=ord))

# Test with special characters
text = "zAb#9!"
result = sort_with_ord_key(text)
print(f"Input: {text}")
print(f"Output: {result}")

# Show the sorting order
chars_with_ascii = [(char, ord(char)) for char in text]
chars_with_ascii.sort(key=lambda x: x[1])
print("\nSorted by ASCII:")
for char, ascii_val in chars_with_ascii:
    print(f"'{char}' ? {ascii_val}")
Input: zAb#9!
Output: !#9Abz

Sorted by ASCII:
'!' ? 33
'#' ? 35
'9' ? 57
'A' ? 65
'b' ? 98
'z' ? 122

Comparison

Method Time Complexity Space Complexity Best For
sorted() O(n log n) O(n) Simple, readable code
Frequency Array O(n) O(128) Large strings with limited character set
Custom Key O(n log n) O(n) When you need explicit ASCII sorting

Conclusion

Python's sorted() function automatically sorts characters by ASCII values, making it the simplest solution. For performance with large strings containing limited characters, use the frequency array approach with O(n) time complexity.

Updated on: 2026-03-27T11:52:50+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements