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.
// Function to sort strings lexicographicallyintlexicographic_sort(constchar*a,constchar*b){returnstrcmp(a,b);}// Function to sort strings in reverse lexicographical orderintlexicographic_sort_reverse(constchar*a,constchar*b){returnstrcmp(b,a);}// Function to sort strings by the number of distinct charactersintsort_by_number_of_distinct_characters(constchar*a,constchar*b){// Count distinct characters in string aintcount_a[256]={0};intdistinct_count_a=0;for(constchar*p=a;*p!='\0';p++){if(!count_a[(unsignedchar)*p]){distinct_count_a++;count_a[(unsignedchar)*p]=1;}}// Count distinct characters in string bintcount_b[256]={0};intdistinct_count_b=0;for(constchar*p=b;*p!='\0';p++){if(!count_b[(unsignedchar)*p]){distinct_count_b++;count_b[(unsignedchar)*p]=1;}}// Compare distinct character countsif(distinct_count_a==distinct_count_b){returnlexicographic_sort(a,b);}returndistinct_count_a-distinct_count_b;}// Function to sort strings by their lengthsintsort_by_length(constchar*a,constchar*b){intlen_a=strlen(a);intlen_b=strlen(b);if(len_a==len_b){returnlexicographic_sort(a,b);}returnlen_a-len_b;}// Function to sort an array of strings using a given comparison functionvoidstring_sort(char**arr,constintlen,int(*cmp_func)(constchar*a,constchar*b)){for(inti=0;i<len-1;i++){for(intj=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;}}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sorting Array of Strings
You are viewing a single comment's thread. Return to all comments →
c