We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- C
- Functions
- Sorting Array of Strings
- Discussions
Sorting Array of Strings
Sorting Array of Strings
Sort by
recency
|
240 Discussions
|
Please Login in order to post a comment
include
include
include
// Comparison functions int lexicographic_sort(const char* a, const char* b) { return strcmp(a, b); }
int lexicographic_sort_reverse(const char* a, const char* b) { return strcmp(b, a); }
int sort_by_length(const char* a, const char* b) { int len_a = strlen(a); int len_b = strlen(b); if (len_a != len_b) return len_a - len_b; return strcmp(a, b); }
int sort_by_length_reverse(const char* a, const char* b) { int len_a = strlen(a); int len_b = strlen(b); if (len_a != len_b) return len_b - len_a; return strcmp(b, a); }
// You might see this one in some variants: sort by number of distinct characters int count_distinct(const char* s) { int freq[26] = {0}; int count = 0; for (int i = 0; s[i]; i++) { if (!freq[s[i] - 'a']) { freq[s[i] - 'a'] = 1; count++; } } return count; }
int sort_by_number_of_distinct_characters(const char* a, const char b) { int count_a = count_distinct(a); int count_b = count_distinct(b); if (count_a != count_b) return count_a - count_b; return strcmp(a, b); }
// Generic sorting function using function pointer void string_sort(const char **arr, const int cnt, int (cmp_func)(const char, const char*)) { // Simple bubble sort - acceptable since constraints are small (n <= 100 usually) for (int i = 0; i < cnt; i++) { for (int j = i + 1; j < cnt; j++) { if (cmp_func(arr[i], arr[j]) > 0) { const char* temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } }
// The rest of the code (main, input handling) is usually provided by HackerRank
Here is my take on this.
Here is Sorting Arrays of Strings solution in c - https://programmingoneonone.com/hackerrank-sorting-array-of-strings-solution-in-c.html