HackerRank C- Sorting Array of Strings




The output consists of the strings sorted according to the four comparsion functions in the order mentioned in code



  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int lexicographic_sort(const char* a, const char* b){
  5. return strcmp(a, b) > 0;
  6. }
  7. int lexicographic_sort_reverse(const char* a, const char* b){
  8. return strcmp(a, b) <= 0;
  9. }
  10. int sort_by_number_of_distinct_characters(const char* a, const char* b){
  11. int c1 = 0, c2 = 0;
  12. int hsh1[26] = {0}, hsh2[26] = {0};
  13. int n1 = strlen(a);
  14. int n2 = strlen(b);
  15. for(int i = 0; i < n1; i++){
  16. hsh1[a[i] - 'a'] = 1;
  17. }
  18. for(int i = 0; i < n2; i++){
  19. hsh2[b[i] - 'a'] = 1;
  20. }
  21. for(int i = 0; i < 26; i++){
  22. if(hsh1[i])
  23. c1++;
  24. if(hsh2[i])
  25. c2++;
  26. }
  27. if( c1 != c2)
  28. return c1 > c2;
  29. else
  30. return strcmp(a, b) > 0;
  31. }
  32. int sort_by_length(const char* a, const char* b){
  33. if(strlen(a) != strlen(b))
  34. return strlen(a) > strlen(b);
  35. else
  36. return strcmp(a, b) > 0;
  37. }
  38. void string_sort(char** arr,const int len,int (*cmp_func)(const char* a, const char* b)){
  39. for(int i = 1; i < len; i++){
  40. int j = i;
  41. char* p = arr[i];
  42. while(j > 0){
  43. if((*cmp_func)(arr[j-1],p) > 0 )
  44. arr[j] = arr[j-1];
  45. else
  46. break;
  47. j--;
  48. }
  49. arr[j] = p;
  50. }
  51. }
  52. }
  53. int main()
  54. {
  55. int n;
  56. scanf("%d", &n);
  57. char** arr;
  58. arr = (char**)malloc(n * sizeof(char*));
  59. for(int i = 0; i < n; i++){
  60. *(arr + i) = malloc(1024 * sizeof(char));
  61. scanf("%s", *(arr + i));
  62. *(arr + i) = realloc(*(arr + i), strlen(*(arr + i)) + 1);
  63. }
  64. string_sort(arr, n, lexicographic_sort);
  65. for(int i = 0; i < n; i++)
  66. printf("%s\n", arr[i]);
  67. printf("\n");
  68. string_sort(arr, n, lexicographic_sort_reverse);
  69. for(int i = 0; i < n; i++)
  70. printf("%s\n", arr[i]);
  71. printf("\n");
  72. string_sort(arr, n, sort_by_length);
  73. for(int i = 0; i < n; i++)
  74. printf("%s\n", arr[i]);
  75. printf("\n");
  76. string_sort(arr, n, sort_by_number_of_distinct_characters);
  77. for(int i = 0; i < n; i++)
  78. printf("%s\n", arr[i]);
  79. printf("\n");
  80. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube