Q12. Write an code and algorithm to sort string of characters in dictionary order
Solution : Given a string contain lowercase character from a to z and our task is to sort them in dictionary order.
String :- A string is a sequence of characters terminated with a null character \0 .
For example: char lfc[] = “alfatechlab”;
Algorithm for sort string of characters in dictionary order
//Algorithm To Sort String Of Characters
START
Step 1 -> Take string as input str.
Step 2 -> Store the count of each character in one array ARR, index 0 corresponding to a and so on.
Step 3 -> Now repeat loop I till the end of array ARR
Step 4 -> Repeat inner loop on the basis of value of ARR[I]
Step 5 -> Print (‘a’ + I)
Step 6 -> End Inner loop
Step 7 -> End Loop
STOP
Code for sort string of characters in dictionary order
//C Program To Sort String Of Characters.
#include <stdio.h>
int main()
{
char str[20]=”alfatechlab”;
int len=sizeof(str);
int charCount[26] = {0};
for (int i=0; i<len; i++)
charCount[str[i]-‘a’]++;
for (int i=0;i<26;i++)
for (int j=0;j<charCount[i];j++)
printf(“%c”,(char)(‘a’+i));
return 0;
}
//C++ Program To Sort String Of Characters.
#include <iostream>
using namespace std;
int main()
{
string str = “alfatechlab”;
int charCount[26] = {0};
for (int i=0; i<str.length(); i++)
charCount[str[i]-‘a’]++;
for (int i=0;i<26;i++)
for (int j=0;j<charCount[i];j++)
cout << (char)(‘a’+i);
return 0;
}
//Java Program To Sort String Of Characters.
public class LFC
{
public static void main(String[] args) {
String str=”alfatechlab”;
int alphabet[] = new int[26];
for (char x : str.toCharArray()) {
alphabet[x – ‘a’]++;
}
for (int i = 0; i < 26; i++) {
for (int j = 0; j < alphabet[i]; j++) {
System.out.print((char) (i + ‘a’));
}
}
}
}
//Python Program To Sort String Of Characters.
str1=”alfatechlab”
charCount = [0 for i in range(26)]
for i in range(0, len(str1), 1):
charCount[ord(str1[i]) – ord(‘a’)] += 1
for i in range(0, 26, 1):
for j in range(0, charCount[i], 1):
print(chr(ord(‘a’) + i), end = “”)
//PHP Program To Sort String Of Characters.
<?php
$str = ‘alfatechlab’;
$strsplit = preg_split(‘//u’, $str);
sort($strsplit);
echo implode(”, $strsplit);
?>
Output
aaabcefhllt
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number