Insertion sort while removing duplicates in C++ <p>I am having trouble with my insertion sort method. It loops over an array of elements of a custom struct that holds the word and the number of occurrences. The array length is fixed at 1000. The sort removes duplicates. It think the problem is in the swap when a duplcate is found but I am using the same function for the sorting swap. I have played with it for a while and I just can seem to get it to work.</p> <p>My program outputs the entire list, using length variable and outputs the following:</p> <pre><code>word occurences hello 500 hello 500 </code></pre> <p>I know that the array holds 1000 elements of the word hello, so this output if confusing me.</p> <pre><code>void sortAndRemoveDuplicates(Word WordArray [],int &amp;length){ /* Description: Sort the word array, removing duplicates */ for(int index=0;index&lt;length-1;index++){ int idxMin=index; for(int idx=index;idx&lt;length;idx++){ if(WordArray[idx].word&lt;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 &amp;x, Word &amp;y){ /* Description: Swap two words */ Word temp; temp=x; x=y; y=temp; }; void printResults (string &amp;filename, int &amp;charCount, int &amp;lineCount, int wordCount, Word WordArray[],int &amp;length){ /* Description: Print the results of the program to cout */ cout&lt;&lt;"\tResults\n"; cout&lt;&lt;"Filename: "&lt;&lt;filename&lt;&lt;"\n"; cout&lt;&lt;"Character Count: "&lt;&lt;charCount&lt;&lt;"\n"; cout&lt;&lt;"Line Count: "&lt;&lt;lineCount&lt;&lt;"\n"; cout&lt;&lt;"Word Count:"&lt;&lt;wordCount&lt;&lt;"\n"; cout&lt;&lt;"\tWord\tCount\n"; int i=0; while(i&lt;(length)){ cout&lt;&lt;"\t"; cout&lt;&lt;WordArray[i].word&lt;&lt;"\t"&lt;&lt;WordArray[i].wordCount&lt;&lt;"\n"; i++; } }; </code></pre> <p>Thanks</p>