We will sort the strings using the sort function from the STL. We will use the comparator less<int>() for ascending sorting and the comparator greater<int>() for descending sorting.
Algorithm Implementation
Declare a working character array.
#define MAX 101
char s[MAX];Read the string.
gets(s);Sort the letters in ascending order. Output the resulting string.
sort(s,s+strlen(s),less<int>());
puts(s);Sort the letters in descending order. Output the resulting string.
sort(s,s+strlen(s),greater<int>());
puts(s);Algorithm Implementation – string
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string s;
int main(void)
{
cin >> s;
sort(s.begin(),s.end(),less<int>());
cout << s << "\n";
sort(s.begin(),s.end(),greater<int>());
cout << s << "\n";
return 0;
}Algorithm Implementation – C, swap sort
#include <stdio.h>
#include <string.h>
char s[101], temp;
int i, j, n;
int main(void)
{
gets(s);
n = strlen(s);
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (s[i] > s[j])
{
temp = s[i]; s[i] = s[j]; s[j] = temp;
}
puts(s);
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (s[i] < s[j])
{
temp = s[i]; s[i] = s[j]; s[j] = temp;
}
puts(s);
return 0;
}Java Implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
String s[] = con.nextLine().split("");
// s = {"q", "w", "e", "r", "t", "y"}
Arrays.sort(s);
System.out.println(String.join("", s));
Arrays.sort(s,Collections.reverseOrder());
System.out.println(String.join("", s));
con.close();
}
}Python Implementation
s = input()
print(''.join(sorted(s)))
print(''.join(sorted(s, reverse = True)))Python Implementation – sorting
l = list(input())
l.sort()
print(''.join(l))
l.sort(reverse = True)
print(''.join(l))