Sorting Array of Strings

  • + 0 comments

    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_number_of_distinct_characters(const char* a, const char* b) { int count_a = 0, count_b = 0; int freq_a[26] = {0}, freq_b[26] = {0};

    for (int i = 0; i < strlen(a); i++) {
        if (freq_a[a[i] - 'a'] == 0) {
            count_a++;
            freq_a[a[i] - 'a'] = 1;
        }
    }
    
    for (int i = 0; i < strlen(b); i++) {
        if (freq_b[b[i] - 'a'] == 0) {
            count_b++;
            freq_b[b[i] - 'a'] = 1;
        }
    }
    
    if (count_a == count_b) return strcmp(a, b); 
    return count_a - count_b;
    

    }

    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 strcmp(a, b);
    } else {
        return (len_a - len_b);
    }
    

    }

    void string_sort(char** arr,const int len,int (cmp_func)(const char a, const char* b)){ // Bubble Sort for(int i = 0; i < len - 1; i++){ for(int j = 0; j < len - i - 1; j++){ if (cmp_func(arr[j], arr[j + 1]) > 0) { char* temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }