arrays - Insertion sort while removing duplicates in C++ -
i having problem insertion sort method. loops on array of elements of custom struct holds word , number of occurrences. array length fixed @ 1000. sort removes duplicates. think problem in swap when duplcate found using same function sorting swap. have played while , can seem work.
my programme outputs entire list, using length variable , outputs following:
word occurences hello 500 hello 500
i know array holds 1000 elements of word hello, output if confusing me.
void sortandremoveduplicates(word wordarray [],int &length){ /* description: sort word array, removing duplicates */ for(int index=0;index<length-1;index++){ int idxmin=index; for(int idx=index;idx<length;idx++){ if(wordarray[idx].word<wordarray[idxmin].word){ idxmin=idx; } } // if duplicate if(wordarray[idxmin].word==wordarray[index-1].word){ wordarray[index-1].wordcount++; swap(wordarray[idxmin],wordarray[index]); length--; index--; } if(idxmin!=index){ swap(wordarray[idxmin],wordarray[index]); } } }; void swap(word &x, word &y){ /* description: swap 2 words */ word temp; temp=x; x=y; y=temp; }; void printresults (string &filename, int &charcount, int &linecount, int wordcount, word wordarray[],int &length){ /* description: print results of programme cout */ cout<<"\tresults\n"; cout<<"filename: "<<filename<<"\n"; cout<<"character count: "<<charcount<<"\n"; cout<<"line count: "<<linecount<<"\n"; cout<<"word count:"<<wordcount<<"\n"; cout<<"\tword\tcount\n"; int i=0; while(i<(length)){ cout<<"\t"; cout<<wordarray[i].word<<"\t"<<wordarray[i].wordcount<<"\n"; i++; } };
thanks
c++ arrays sorting insertion-sort
No comments:
Post a Comment