按c长度稳定排序
发布时间:2020-12-16 07:14:26 所属栏目:百科 来源:网络整理
导读:我正在编写一个编码问题,我必须按字长来排序一个单词数组(指向字符串的指针).我知道使用一些索引操作的代码,但是想要检查逻辑以查看我是否正确.这是我到目前为止的代码. void len_sort(char** words,int num_words){ int index=0; int isSorted=0; int strin
我正在编写一个编码问题,我必须按字长来排序一个单词数组(指向字符串的指针).我知道使用一些索引操作的代码,但是想要检查逻辑以查看我是否正确.这是我到目前为止的代码.
void len_sort(char** words,int num_words) { int index=0; int isSorted=0; int string1_len; int string2_len; while(isSorted==0) { for(index=0;index<num_words;index++) { printf("%sn",words[index]); string1_len=strlen(words[index]); if((index+1)==num_words) string2_len=strlen(words[index]); else string2_len=strlen(words[index+1]); if(string1_len<string2_len) { swap(words[index],words[index+1]); } } isSorted=1; for(index=0;index<num_words;index++) { string1_len=strlen(words[index]); if(index+1==num_words) string2_len=strlen(words[index]); else string2_len=strlen(words[index+1]); if(string1_len>string2_len) { isSorted=0; } } } } void swap(char* word1,char* word2) { char* temp; word1=word2; word2=temp; } 我不需要按字母顺序排序,我需要保持单词在数组中的顺序.例如:如果我有类似的东西 car x horse a 我的输出应该如下: x a car horse 保持x在数组中的a之前是真的. 解决方法
交换功能没有做任何有意义的事情.如果要交换两个指针,它应该是这样的:
void swap(char **word1,char **word2) { char *temp; temp = *word1; *word1 = *word2; *word2 = temp; } 现在,为了稳定排序,我们只能交换前一个是否比下一个长.每次交换后,数组将更加分类一步.我们从一开始就开始 void len_sort(char** words,int num_words) { int i = 0; //start from the beginning. while(i < num_words-1) //till the last pair. { if(strlen(words[i]) > strlen(words[i+1])){//if a mismatch occur swap(&words[i],&words[i+1]);//fix it i = -1;//and start from the beginning } i++;//so far sorted,try next pair } } 测试: int main() { char d[][30] = {"car","x","horse","a"}; char *s[4]; int i; //our function sort through pointer for(i=0; i<4; i++) s[i] = d[i]; len_sort(s,4); for(i=0; i<4; i++) printf("%s ",s[i]); puts(""); return 0; } OUTPUT: x a car horse (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |