Note that there are some explanatory texts on larger screens.

plurals
  1. POCounting Sort infinite loop
    primarykey
    data
    text
    <p>I am writing a counting sort function and when I run it, a window pops up saying "filename.exe has stopped working". After debugging it looks like it is getting stuck in the second <code>for</code> loop. What really confuses me, is if I set <code>maxInt</code> to any number greater than 130000 it works, but if its 130000 or lower than I get that error message. The file I'm using to sort only has about 20 numbers.</p> <pre><code>#include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; using namespace std; std::string file = ""; std::vector&lt;int&gt; numbers; void CountingSort(vector&lt;int&gt; &amp;numbers); int main() { std::cout &lt;&lt; "Which file would you like to sort?\n"; std::cin &gt;&gt; file; std::ifstream in(file.c_str()); // Read all the ints from in: std::copy(std::istream_iterator&lt;int&gt;(in), std::istream_iterator&lt;int&gt;(), std::back_inserter(numbers)); CountingSort(numbers); // Print the vector with tab separators: std::copy(numbers.begin(), numbers.end(), std::ostream_iterator&lt;int&gt;(std::cout, "\t")); std::cout &lt;&lt; std::endl; return 0; } struct CalcMaxInt { int maxInt; CalcMaxInt () : maxInt(0) {} void operator () (int i) { if (i &gt; maxInt) maxInt = i; } }; void CountingSort(vector&lt;int&gt;&amp; numbers) { CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt()); //int maxInt = cmi.maxInt + 1; int maxInt = 130001; vector &lt;int&gt; temp1(maxInt); vector &lt;int&gt; temp2(maxInt); for (int i = 0; i &lt; numbers.size(); i++) { temp2[numbers[i]] = temp2[numbers[i]] + 1; } for (int i = 1; i &lt;= maxInt; i++) { temp2[i] = temp2[i] + temp2[i - 1]; } for (int i = numbers.size() - 1; i &gt;= 0; i--) { temp1[temp2[numbers[i]] - 1] = numbers[i]; temp2[numbers[i]] = temp2[numbers[i]] -1; } for (int i =0;i&lt;numbers.size();i++) { numbers[i]=temp1[i]; } return; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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