Sort Characters in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

/* C — Sort Characters (spaces removed) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int cmp(const void *a, const void *b){
    return (*(const unsigned char*)a) - (*(const unsigned char*)b);
}

int main(){
    char s[1005];
    if(!fgets(s, sizeof s, stdin)) return 0;
    size_t n = strlen(s);
    if(n && s[n-1]=='\n') s[--n] = '\0';

    char arr[1005];
    int len = 0;
    for(size_t i=0; s[i]; ++i)
        if(s[i] != ' ')
            arr[len++] = s[i];

    if(len==0){ printf("\n"); return 0; }
    qsort(arr, len, sizeof(char), cmp);
    arr[len] = '\0';
    printf("%s\n", arr);
    return 0;
}

C Output

Input:  
hello world  

Output:  
dehllloorw


C++ Program

// C++ — Sort Characters (spaces removed)
#include <bits/stdc++.h>
using namespace std;
int main(){
    string s;
    if(!getline(cin, s)) return 0;
    string t;
    for(char c: s) if(c!=' ') t.push_back(c);
    sort(t.begin(), t.end());          // ASCII order
    cout << t << '\n';
    return 0;
}

C++ Output

Input:  
banana 

Output:  
aaabnn


JAVA Program

// Java — Sort Characters (spaces removed)
import java.util.Arrays;
import java.io.*;

class Main {
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s = br.readLine();
    if(s == null) return;
    String t = s.replace(" ", "");
    char[] a = t.toCharArray();
    Arrays.sort(a);                    // ASCII order
    System.out.println(new String(a));
  }
}

JAVA Output

Input:  
The classroom

Output:  
Tacehlmoorss


Python Program

# Python — Sort Characters (spaces removed)
s = input().rstrip("\n")
t = s.replace(" ", "")
print("".join(sorted(t)))

Python Output

Input:  
apple pie

Output:  
aeeilpp


In-Depth Explanation (very detailed)
Example
If you input hello world the program initially deletes spaces → helloworld. Alphabetical order of the characters by code point (ASCII for plain ASCII text) gives d e h l l l o o r w together as dehllloorw. With banana you get aaabnn since the three as appear first, followed by b, then two ns.

What the programs do (step-by-step)
Read the input string (full line).

Erase spaces (so we sort only the characters you are interested in — this is a typical requirement; see alternative versions below if you need spaces maintained or treated differently).

Sort the rest of the characters by the language's sort routine (qsort in C, std::sort in C++, Arrays.sort in Java, sorted() in Python). The sort is by code point: uppercase letters precede lowercase letters in ASCII.

Print the joined, ordered characters as a new string.

Why delete spaces by default here?
Including spaces in sorting tends to put space characters at the beginning of the output (space is a low code point character). Most learners will anticipate the significant content (letters, numbers, punctuation) being displayed sorted, so I employed the standard form: strip spaces and then sort. If you prefer a different behavior (don't strip spaces, leave them in original positions, or treat them as normal characters), you can apply one of the alternate forms below.

Variations and shared requirements
Sort with spaces: do not include the if (c != ' ') restriction; spaces will appear at the beginning of the output since their code point is low.

Sort but spaces do not change position: gather letters, sort them, and put them back in non-space positions. Handy if you want words to stay spaced but letters within words sorted.

Case-insensitive sort retaining original case: sort on tolower(c) as key but in case of equality retain original letter order or favor upper/lower tie-breaker.

Sort alphabetic characters only: filter to isalpha(c) then sort; numbers and punctuation excluded or processed separately.

Stable vs unstable sort: internal sorts are stable in certain languages (Python's sorted() is stable). For ASCII characters this generally does not matter unless you have repeated keys and want to maintain original relative order.

Complexity and performance
The naive algorithm employs a general comparison sort: O(n log n) time (n = number of characters after filtering) and O(n) additional space in most implementations.

If the input character set is small and fixed (e.g., only lowercase English letters), you can use counting sort / frequency array which takes O(n + k) time (k = alphabet size) and O(k) space — practically O(n) for fixed k. This can be used in interviews to optimize from O(n log n) to O(n).

Memory complexity is generally O(n) for the working buffers.

Edge cases and things to watch
Empty string → print empty line.

String of spaces only → after removal length = 0 → print empty line.

Unicode / multibyte characters: the code above assumes the input is bytes/char units. For multibyte Unicode characters you should treat code points carefully (e.g., in C/C++ use Unicode libraries; in Python 3 sorted() operates on Unicode codepoints but bear in mind normalization). Code point order may not reflect natural language collation orders (locale-aware sort is distinct).

Upper and lower case: ASCII orders uppercase (A–Z) first, then lowercase (a–z). If A and a should be regarded as equal for sorting purposes, do case-folding (lower()/tolower()) on keys and then re-install case if necessary.

Long strings: default sorts can cope with large inputs but for very long strings or small alphabet use counting/frequency algorithms to optimize speed and memory usage.

Implementation tips & micro-optimizations
Counting sort for small alphabets: keep frequency array (e.g., int freq[26] for lower-case letters), then reconstruct sorted string by iterating frequencies. This takes linear time.

In-place sorting: programming languages with mutability in strings (C/C++ char arrays, Python can't in-place for str) allow you to sort in-place to conserve memory.

Avoid repeated allocations: pre-reserve capacity in containers (C++ string::reserve) when constructing buffers for large input to avoid reallocations.

Use language utilities: Java Arrays.sort(char[]), Python sorted(), C++ std::sort are very optimized and used in interviews for simplicity unless asked to code a custom sort.

Interview significance
This question tests:

Ability to read and convert strings.

Knowledge of sort APIs and their time complexity.

Knowledge of alternatives (frequency/counting sort) and when they are more appropriate.
Follow-up interview questions usually include: sort only letters, sort ignoring case, stable sort with duplicates, or do it in O(n) for small alphabets. Having ability to talk about count arrays or radix/counting sort is helpful.

Applications in the real world
Data normalization: normalizing text by sorting tokens/characters for comparison (e.g., canonical forms, fingerprinting).

Searching / matching: when order isn't important but composition is (anagram detection uses similar concepts).

UI/UX features: alphabetical lists, auto-sorting characters for games/puzzles.

Preprocessing: in text analysis, occasionally character or token sorting is part of a normalization pipeline.

Examples & test cases to attempt
"hello world" → dehllloorw (our default operation: spaces stripped)

"banana" → aaabnn

"The classroom" → Tacehlmoorss (see T precedes lowercase letters)

"a A a" → depending on design: if you strip spaces and sort by ASCII → Aaa (upper first). If you want case-insensitive sort, convert to lower then sort → aaa.

Non-ASCII: "ñaá" — watch Unicode; sorted order locale-dependent and code point-dependent.

How to expand this into exercises
Write a variant that retains spaces but sorts characters in words only.

Perform case-insensitive sort but retain original case of letters.

Perform counting sort version for lowercase-a–z only (O(n) time).

Add locale-aware sorting for natural language order (includes libraries).

SEO-friendly wrap-up
Sorting characters in a string is a basic string-manipulation task that teaches sorting APIs, frequency-based optimizations, case/locale handling, and edge-case thinking. The code and examples in C, C++, Java, and Python demonstrate how to do a simple ASCII-based sort (with default removal of spaces). For production-level text processing use Unicode normalization and locale-aware collation; for interview-level optimization use counting/radix sort for fixed alphabets. Practice variations such as maintaining spaces or case-insensitive ordering to further strengthen your expertise and prepare yourself for coding interviews and actual text-processing applications.