Sorting a string alphabetically is a common programming task that helps in organizing characters in lexicographical order. In this article, we will explore two methods to achieve this: manually swapping characters and using built-in functions.
Example 1:
face
acef
Example 2:
focus
cfosu
This method manually compares and swaps characters to achieve alphabetical order.
Algorithm:
Code Implementation (C):
#include <stdio.h>
#include <string.h>
voidsortString(charstr[]) {
inti, j;
chartemp;
intlen=strlen(str);
for (i=0; i<len-1; i++) {
for (j=i+1; j<len; j++) {
if (str[i] >str[j]) {
temp=str[i];
str[i] =str[j];
str[j] =temp;
}
}
}
printf(“Sorted String: %s\n”, str);
}
intmain() {
charstr[] =”focus”;
sortString(str);
return0;
}
Time Complexity: O(n^2)
(due to nested loops)
This method leverages built-in sorting functions for better efficiency.
Algorithm:
qsort()
or equivalent sorting function.Code Implementation (Python):
defsort_string(s):
return””.join(sorted(s))
string=”focus”
print(“Sorted String:”,sort_string(string))
Time Complexity: O(n log n)
(due to efficient sorting algorithms like QuickSort or MergeSort)
Approach | Time Complexity | Space Complexity | Suitability |
---|---|---|---|
Swapping characters | O(n^2) | O(1) | Small strings, simple logic |
Library function | O(n log n) | O(n) | Large strings, optimized performance |
Would you like solutions for these problems? Let us know!
Sorting a string alphabetically is a fundamental programming problem with multiple solutions:
Choosing the right approach depends on performance needs and ease of implementation.