Program to sort a string in alphabetical order | FACE Prep

Program to sort a string in alphabetical order | FACE Prep

Sort a String in Alphabetical Order | Code Examples

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.

Understanding the Problem

Example 1:

  • Input: face
  • Output: acef

Example 2:

  • Input: focus
  • Output: cfosu

Methods to Sort a String Alphabetically

Method 1: Sorting by Swapping Characters

This method manually compares and swaps characters to achieve alphabetical order.

Algorithm:

  1. Convert the string into an array of characters.
  2. Iterate through the characters and compare each one with the rest.
  3. If a character is greater than another, swap them.
  4. Continue the process until all characters are in order.
  5. Convert the array back into a string and display the result.

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)


Method 2: Using Standard Library Functions

This method leverages built-in sorting functions for better efficiency.

Algorithm:

  1. Convert the string into an array of characters.
  2. Use the standard library function qsort() or equivalent sorting function.
  3. Print the sorted string.

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)


Comparison of Methods

ApproachTime ComplexitySpace ComplexitySuitability
Swapping charactersO(n^2)O(1)Small strings, simple logic
Library functionO(n log n)O(n)Large strings, optimized performance

Similar String-Based Problems to Solve

  • Basic string operations
  • Counting the frequency of characters in a string
  • Finding non-repeating characters in a string
  • Checking if a string is a palindrome

Would you like solutions for these problems? Let us know!


Conclusion

Sorting a string alphabetically is a fundamental programming problem with multiple solutions:

  • Manual Swapping: Simple but inefficient.
  • Library Functions: Efficient and preferred for large datasets.

Choosing the right approach depends on performance needs and ease of implementation.

Program to sort a string in alphabetical order | FACE Prep
c