×

Data Structure Using C & C++

Print the characters in sorted order using hash table

Here is the program to print the characters in sorted order using hash table using C:

C program to print the characters in sorted order using hash table

#include <stdio.h>
#include <string.h>

#define MAX_CHAR 256

void sortAndPrintCharacters(char * str) {
  int hashTable[MAX_CHAR] = {0};

  // Count the occurrences of each character
  for (int i = 0; str[i]; i++) {
    hashTable[(unsigned char) str[i]]++;
  }

  // Print characters in sorted order
  for (int i = 0; i < MAX_CHAR; i++) {
    if (hashTable[i] > 0) {
      for (int j = 0; j < hashTable[i]; j++) {
        printf("%c", i);
      }
    }
  }
}

int main() {
  char str[100];

  printf("Enter a string: ");
  fgets(str, sizeof(str), stdin);

  // Remove newline character if present
  str[strcspn(str, "\n")] = 0;

  sortAndPrintCharacters(str);

  return 0;
}

Output

[?2004l
Enter a string: IncludeHelp.com
.HIccdeellmnopu[?2004h

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.