Sort the string as per the ASCII values of the characters


ASCII Values

ASCII (American Standard Code for Information Interchange) is the most common character encoding format for text data in computers and on the internet. In standard ASCII-encoded data, there are unique values for 256 alphabetic, numeric, or special additional characters and control codes.

Problem Statement

Now, in this problem, we need to find the sorted string as per ASCII values of the characters in increasing order, where the string will be the input given to us by the user. Let us see how we should proceed to solve this problem.

Let’s try to understand this problem with the help of some examples.

Input

s = "$%7wjk()"

Output

“$%()7jkw”

Explanation − The ASCII values of the characters of the given string are given as follows −

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

Thus, in the increasing order as per ASCII code values the string would become “$%()7jkw”

Input

s = "#m 0f)nk"

Output

“#)0fkmn”

Explanation − The ASCII values of the characters of the given string are given as follows −

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

Thus, in the increasing order as per ASCII code values the string would become "#)0fkmn".

Problem Explanation

Let’s try to understand the problem and find its solution. We know that there are 256 characters in the ASCII table in which each character has a unique value or position. So our basic goal is to sort the characters accordingly. We can use the inbuilt sort function by using an external function that can be used to fulfill our goal. Another method is to make a frequency vector and store the frequencies of each character in that array. Using this frequency vector and the ASCII values, we can get our new string.

Approach-1: Using Frequency Vector

Algorithm

  • Make a frequency vector of size 256, as the total characters in the ASCII table are 256, and initiate the whole vector with zero.

  • Run a loop to store the frequency of each character of the given string.

  • Now define an output string that is initially empty.

  • Run another loop that will traverse the frequency vector and hence we can get the output string by typecasting the ith position frequency_vector[i] number of times.

  • Return the output string as our final result.

Example

Following is the implementation of the above approach in C++ language −

#include <bits/stdc++.h>
using namespace std;
// Function to Sort the string as per ASCII values of the characters
string Helper(string s){
   // Define the size of the given string
	int size = s.length();
	// Define a frequency vector of size 256, which is the same as the size of the characters as per the ASCII table, and initiate the value of the vector as 0
	vector<int> v(256, 0);
	// Run a loop to count the frequency of each character of the string
	for (int i = 0; i < size; i++) {
		v[s[i]]++;
	}	
	// Declare a string, initially empty, to find the final output
	string ans = "";
	// Run another loop to get the final output in accordance with the ASCII table
	for (int i = 0; i < 256; i++) {
		for (int j = 0; j < v[i]; j++)
		// Typecast the integer value to the character value to include it in the loop
			ans = ans + (char)i;
	}
	// Return the final output
	return ans;
}
int main(){
   // Give input as a string by the user
	string s = "$%7wjk()";
	// Call Helper function to perform the remaining tasks
	cout<< "The sorted string as per ASCII values of the characters is: " << Helper(s);
	return 0;
}

Output

The sorted string as per ASCII values of the characters is: $%()7jkw

Complexities for the Above Code

  • Time complexity − O(n); where n is the size of the string. Here, the actual time complexity is O(n * 256) but we can take it as O(n) as 256 can be treated as a constant, say k and O(k * n) is treated as O(n) only.

  • Space complexity − O(256); as the only extra space occupied here is the space of the frequency array and its size is 256.

Approach-2: Solution by Using the Inbuilt Sort Function

Algorithm

  • Define an external comparison function that will be used in the sorting function to sort the characters according to the ASCII values, that is return the character whose int typecasted value is less than the others.

  • Now, in the helper function use the inbuilt sort function and use an extra parameter, the comparison function to get the order correctly.

  • Call the helper function and get the final string output.

Example

The following are implementations of the above approach in various programming languages −

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
// Comparison Function to sort the string as per ASCII values of the characters
int comparison(const void* a, const void* b){
   return (*(char*)a - *(char*)b);
}

// Function to sort the string as per ASCII values of the characters
void Helper(char* s){
   size_t len = strlen(s);
   qsort(s, len, sizeof(char), comparison);
}
int main(){
   // Give input as a string by the user
   char s[] = "$%7wjk()";
   // Call Helper function to perform the sorting
   Helper(s);
   printf("The sorted string as per ASCII values of the characters is: %s", s);
   return 0;
}

Output

The sorted string as per ASCII values of the characters is: $%()7jkw
#include <bits/stdc++.h>
using namespace std;
// Comparison Function to sort the string as per ASCII values of the characters
bool comparison(char ch1, char ch2){
   return int(ch1) <= int(ch2);
}
// Function to sort the string as per ASCII values of the characters
string Helper(string s){
   // Sort the string s with the help of the inbuilt function sort()
   sort(s.begin(), s.end(), comparison);
   // Return the final output string s
   return s;
}
int main(){
   // Give input as a string by the user
   string s = "$%7wjk()";
   // Call Helper function to perform the remaining tasks
   cout<< "The sorted string as per ASCII values of the characters is: " << Helper(s);
   return 0;
}

Output

The sorted string as per ASCII values of the characters is: $%()7jkw
# Comparison Function to sort the string as per ASCII values of the characters
def comparison(ch1, ch2):
   return ord(ch1) <= ord(ch2)

# Function to sort the string as per ASCII values of the characters
def Helper(s):
   # Sort the string s using the sorted() function and the custom comparison function
   s = ''.join(sorted(s, key=lambda x: ord(x)))
   return s

# Give input as a string by the user
s = "$%7wjk()"
# Call Helper function to perform the remaining tasks
print("The sorted string as per ASCII values of the characters is:", Helper(s))

Output

The sorted string as per ASCII values of the characters is: $%()7jkw

Complexities for the Above Code

  • Time complexity − O(log(n)); As we know inbuilt sort function takes O(n * log(n)) time to execute the code. And in this approach, we have used an inbuilt sort function by using an additional comparison function which would sort our characters according to that function.

  • Space complexity − O(1); We have not stored any variable in some data structure in the above code.

Conclusion

In this article, to find the sorted string as per ASCII values of the characters in increasing order. We can solve this problem by two methods. Firstly, we can make a frequency vector of size 256 (the same as the number of characters in the ASCII table) and store all the frequencies of each character, and then by traversing from the back we can get the required string. Another method can be with the help of the inbuilt sort function with the help of an extra parameter passed in the sort function.

Updated on: 22-Jan-2024

869 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements