Note that there are some explanatory texts on larger screens.

plurals
  1. POInsertionSort Algorithm, Whats Wrong with my Code?
    text
    copied!<p>I'm trying out a InsertSort Algorithm for an input of strings stored in a vector. </p> <p>What I do is to input some strings into the vector, Then i use insertionsort to sort the vectors.</p> <p>But I'm not sure why does it not work! Could anyone point me to the right direction? </p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; using namespace std; int main (){ vector &lt;string&gt; names; //vector to store string input; //input is the variable of strings cout&lt;&lt;"Input a list of names \n"; cout&lt;&lt;"To end the list type 'END'" &lt;&lt;endl; while (true){ getline(cin, input); if (input =="END") break; names.push_back(input); //push into vector names } //my insertsort starts here string temp; int i; for (int j = 1; j &lt; names.size(); j++){ i = j - 1; while ((i&gt;0) &amp;&amp; (names[i]&gt;names[j]) ) { names[i+1] = names[i]; i=i-1; } names[i+1] = names[j]; } for (unsigned int i = 0; i&lt;names.size (); i++) cout&lt;&lt;names[i]&lt;&lt;endl; cout&lt;&lt;endl; system("pause"); } </code></pre> <p>Thanks a bunch</p> <p>EDIT: I will be inputing strings for example I will type:</p> <p>Peter Apple Rabbit</p> <p>And my desired output is, in alphabatical order,:</p> <p>Apple Peter Rabbit</p> <p>At the moment with the example input, I get: Peter Apple Rabbit</p> <p>EDIT 3:</p> <p>My insert sort now looks like this:</p> <pre><code> string temp; int i; for (int j = 1; j &lt; names.size(); j++){ i = j - 1; temp = names[j]; while ((i&gt;=0) &amp;&amp; (names[i]&gt;names[j]) ) { names[i+1] = names[i]; i=i-1; } names[i+1] = temp; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload