fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAX_CHAR 256
  6.  
  7. // Structure to store character frequency
  8. struct CharFreq {
  9. char character;
  10. int frequency;
  11. };
  12.  
  13. // Function to compare two character frequencies
  14. int compare(const void* a, const void* b) {
  15. return ((struct CharFreq*)b)->frequency - ((struct CharFreq*)a)->frequency;
  16. }
  17.  
  18. // Function to sort string in descending order based on character frequency
  19. void sortString(char* s) {
  20. // Create an array to store character frequencies
  21. struct CharFreq freq[MAX_CHAR] = {{0, 0}};
  22.  
  23. // Count frequencies of characters in the string
  24. int length = strlen(s);
  25. for (int i = 0; i < length; i++) {
  26. freq[s[i]].character = s[i];
  27. freq[s[i]].frequency++;
  28. }
  29.  
  30. // Sort the array based on character frequency
  31. qsort(freq, MAX_CHAR, sizeof(struct CharFreq), compare);
  32.  
  33. // Construct the sorted string
  34. int index = 0;
  35. for (int i = 0; i < MAX_CHAR; i++) {
  36. while (freq[i].frequency--) {
  37. s[index++] = freq[i].character;
  38. }
  39. }
  40. }
  41.  
  42. int main() {
  43. char s[] = "tree"; // Example string
  44. printf("Original string: %s\n", s);
  45. sortString(s);
  46. printf("String sorted in descending order of frequency: %s\n", s);
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 5304KB
stdin
45
stdout
Original string: tree
String sorted in descending order of frequency: eert