Program to sort string in descending order
Last Updated :
01 Nov, 2022
Given a string, sort it in descending order.
Examples:
Input : alkasingh
Output : snlkihgaa
Input : nupursingh
Output : uusrpnnihg
Input : geeksforgeeks
Output : ssrokkggfeeee
A simple solution is to use library sort function std::sort()
Implementation:
C++
// CPP program to sort a string in descending
// order using library function
#include <bits/stdc++.h>
using namespace std;
void descOrder(string &s)
{
sort(s.begin(), s.end(), greater<char>());
}
int main()
{
string s = "geeksforgeeks";
descOrder(s); // function call
for(int i = 0; i < s.size(); i++)
cout << s[i];
return 0;
}
Java
// Java program to sort a string in descending
// order using library function
import java.util.*;
class GFG
{
static void descOrder(char[] s)
{
Arrays.sort(s);
reverse(s);
}
static void reverse(char[] a)
{
int i, n = a.length;
char t;
for (i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// Driver code
public static void main(String[] args)
{
char[] s = "geeksforgeeks".toCharArray();
descOrder(s); // function call
System.out.println(String.valueOf(s));
}
}
// This code is contributed by 29AjayKumar
Python
# Python program to sort
# a string in descending
# order using library function
def descOrder(s):
s.sort(reverse = True)
str1 = ''.join(s)
print(str1)
def main():
s = list('geeksforgeeks')
# function call
descOrder(s)
if __name__=="__main__":
main()
# This code is contributed by
# prabhat kumar singh
C#
// C# program to sort a string in descending
// order using library function
using System;
class GFG
{
static void descOrder(char[] s)
{
Array.Sort(s);
reverse(s);
}
static void reverse(char[] a)
{
int i, n = a.Length;
char t;
for (i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// Driver code
public static void Main(String[] args)
{
char[] s = "geeksforgeeks".ToCharArray();
descOrder(s); // function call
Console.WriteLine(String.Join("",s));
}
}
// This code is contributed by Rajput-Ji
PHP
<?php
// PHP program to sort a string in descending
// order using library function
function descOrder($s)
{
$s = str_split($s);
rsort($s);
echo implode('', $s);
}
// Driver Code
$s = "geeksforgeeks";
descOrder($s); // function call
// This code is contributed by ita_c
?>
JavaScript
<script>
// JavaScript program to sort
// a string in descending
// order using library function
function descOrder(s) {
s.sort().reverse();
str1 = s.join("");
document.write(str1);
}
var s = "geeksforgeeks";
s = s.split("");
// function call
descOrder(s);
</script>
The time complexity is : O(n log n)
Auxiliary Space: O(1)
An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from 'a' to 'z' in a hashed array. The first index of the hashed array will represent character 'a', second will represent 'b' and so on. Finally, we will simply traverse the hashed array and print the characters from 'z' to 'a' the number of times they occurred in input string.
Below is the implementation of above idea:
C++
// C++ program to sort a string of characters
// in descending order
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// function to print string in sorted order
void sortString(string& str)
{
// Hash array to keep count of characters.
// Initially count of all characters is
// initialized to zero.
int charCount[MAX_CHAR] = { 0 };
// Traverse string and increment
// count of characters
for (int i = 0; i < str.length(); i++)
// 'a'-'a' will be 0, 'b'-'a' will be 1,
// so for location of character in count
// array we will do str[i]-'a'.
charCount[str[i] - 'a']++;
// Traverse the hash array and print
// characters
for (int i = MAX_CHAR - 1; i >= 0; i--)
for (int j = 0; j < charCount[i]; j++)
cout << (char)('a' + i);
}
// Driver program to test above function
int main()
{
string s = "alkasingh";
sortString(s);
return 0;
}
Java
// Java program to sort a string of characters
// in descending order
class GFG
{
static int MAX_CHAR = 26;
// function to print string in sorted order
static void sortString(String str)
{
// Hash array to keep count of characters.
// Initially count of all charters is
// initialized to zero.
int charCount[] = new int[MAX_CHAR];
// Traverse string and increment
// count of characters
// 'a'-'a' will be 0, 'b'-'a' will be 1,
for (int i = 0; i < str.length(); i++)
{
// so for location of character in count
// array we will do str[i]-'a'.
charCount[str.charAt(i) - 'a']++;
}
// Traverse the hash array and print
// characters
for (int i = MAX_CHAR - 1; i >= 0; i--)
{
for (int j = 0; j < charCount[i]; j++)
{
System.out.print((char) ('a' + i));
}
}
}
// Driver code
public static void main(String[] args)
{
String s = "alkasingh";
sortString(s);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program to sort a string of characters
# in descending order
MAX_CHAR = 26;
# function to print string in sorted order
def sortString(str):
# Hash array to keep count of characters.
# Initially count of all charters is
# initialized to zero.
charCount = [0]*MAX_CHAR;
# Traverse string and increment
# count of characters
for i in range(len(str)):
# 'a'-'a' will be 0, 'b'-'a' will be 1,
# so for location of character in count
# array we will do str[i]-'a'.
charCount[ord(str[i]) - ord('a')]+=1;
# Traverse the hash array and print
# characters
for i in range(MAX_CHAR - 1,-1, -1):
for j in range(charCount[i]):
print(chr(97+i),end="");
# Driver program to test above function
s = "alkasingh";
sortString(s);
# This code is contributed by Princi Singh
C#
// C# program to sort a string of characters
// in descending order
using System;
class GFG
{
static int MAX_CHAR = 26;
// function to print string in sorted order
static void sortString(String str)
{
// Hash array to keep count of characters.
// Initially count of all charters is
// initialized to zero.
int []charCount = new int[MAX_CHAR];
// Traverse string and increment
// count of characters
// 'a'-'a' will be 0, 'b'-'a' will be 1,
for (int i = 0; i < str.Length; i++)
{
// so for location of character in
// count array we will do str[i]-'a'.
charCount[str[i] - 'a']++;
}
// Traverse the hash array and print
// characters
for (int i = MAX_CHAR - 1; i >= 0; i--)
{
for (int j = 0; j < charCount[i]; j++)
{
Console.Write((char) ('a' + i));
}
}
}
// Driver code
public static void Main(String[] args)
{
String s = "alkasingh";
sortString(s);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to sort a string of characters
// in descending order
let MAX_CHAR = 26;
// function to print string in sorted order
function sortString(str)
{
// Hash array to keep count of characters.
// Initially count of all charters is
// initialized to zero.
let charCount = new Array(MAX_CHAR);
for(let i = 0; i < charCount.length; i++)
{
charCount[i] = 0;
}
// Traverse string and increment
// count of characters
// 'a'-'a' will be 0, 'b'-'a' will be 1,
for (let i = 0; i < str.length; i++)
{
// so for location of character in count
// array we will do str[i]-'a'.
charCount[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
// Traverse the hash array and print
// characters
for (let i = MAX_CHAR - 1; i >= 0; i--)
{
for (let j = 0; j < charCount[i]; j++)
{
document.write(String.fromCharCode ('a'.charCodeAt(0) + i));
}
}
}
// Driver code
let s = "alkasingh";
sortString(s);
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).
Similar Reads
Sort vector of Numeric Strings in ascending order Given a vector of numeric strings arr[], the task is to sort the given vector of numeric strings in ascending order. Examples: Input: arr[] = {"120000", "2", "33"}Output: {"2", "33", "120000"} Input: arr[] = {"120", "2", "3"}Output: {"2", "3", "120"} Approach: The sort() function in C++ STL is able
5 min read
C Program to Sort an array of names or strings Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings. C #include <stdio.h> #include <stdlib.h> #include <string.
2 min read
Sort a string in increasing order of given priorities Given an alphanumeric string S of length N, the task is to sort the string in increasing order of their priority based on the following conditions: Characters with even ASCII values have higher priority than characters with odd ASCII values.Even digits have higher priority than odd digits.Digits hav
8 min read
Python - Sort words of sentence in ascending order Sorting words in a sentence in ascending order can be useful for tasks like text analysis, data preprocessing, or even fun applications like creating word puzzles. Itâs simple to achieve this using Python. In this article, we will explore different methods to do this.Using sorted() with SplitThe mos
3 min read
Rearrange a string in sorted order followed by the integer sum Given a string containing uppercase alphabets and integer digits (from 0 to 9), the task is to print the alphabets in the order followed by the sum of digits. Examples: Input : AC2BEW3 Output : ABCEW5 Alphabets in the lexicographic order followed by the sum of integers(2 and 3).Recommended PracticeR
6 min read
Sort a string according to the order defined by another string Given two strings (of lowercase letters), a pattern, and a string. The task is to sort strings according to the order defined by the pattern. It may be assumed that the pattern has all characters of the string and all characters in the pattern appear only once. Examples: Input : pat = "bca", str = "
9 min read
Sort an array of Strings according frequency Given an array of strings arr[], the task is to sort the array of strings according to the frequency of each string, in ascending order. If two elements have the same frequency, then they are sorted into lexicographical order. Examples: Input: arr[] = {"Geeks", "for", "Geeks"} Output: {"for", "Geeks
8 min read
Sort an array of strings in ascending order with each string sorted in descending order Given a array of strings S[] of size N (1 ? N ? 105), sort characters of each string in descending order and then print the array of strings in ascending order. Examples: Input: s[] = {"apple", "box", "cat"} Output: pplea tca xob Explanation: Sorting each string in descending order, S[] modifies to
9 min read
Sort an array of strings according to string lengths We are given an array of strings, we need to sort the array in increasing order of string lengths.Examples: Input : {"GeeksforGeeeks", "I", "from", "am"}Output : I am from GeeksforGeeks Input : {"You", "are", "beautiful", "looking"}Output : You are looking beautiful A simple solution is to write our
10 min read
Print words of a string in reverse order Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simp
10 min read