My program does not work

Hi, this is a program meant to do a counting sort, but for some reason, when I run the program, i did not see any result that I cout. I already have a file linked to my ifstream. Thank you.
#include <iostream>
#include <fstream>
using namespace std;

int main(){
int total[INT_MAX], number[101]={0}, x=0, i, j, y, m=0;
ifstream in("data.txt");
while (in>>total[x])x++;

for(i=0; i<=100; i++){
for(j=0; j<=x; j++){
if(total[j] == i){
number[i]++;
}
}
}
for(y=0; y<=100; y++){
while(m<number[y]){
cout<<y<<" ";
m++;
}
}
}
You are crashing your program with that huge array on the local stack. Make it global if you are going to do it that large.

Also, your O(100n) histogram building is very inefficient, kind of defeating the purpose of counting sort.

Finally, your output loop will fail if you do not reset m to zero each time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
using namespace std;

int total[INT_MAX];
int main()
{
  int /*total[INT_MAX],*/ number[101]={0}, x=0, i, j, y, m=0;
  ifstream in("data.txt");
  while (in>>total[x])x++;
  
//  for(i=0; i<=100; i++)
//  {
//    for(j=0; j<=x; j++)
//    {
//      if(total[j] == i)
//      {
//        number[i]++;
//      }
//    }
//  }
  for (i=0; i<x; i++)
  {
    number[total[i]] += 1;
  }
  
  for(y=0; y<=100; y++)
  {
    m = 0;
    while(m<number[y])
    {
      cout<<y<<" ";
      m++;
    }
  }
}

P.S. You really should chose some better names for stuff. Like input[] and histogram[] and input_size and the like.

Hope this helps.
Just riffing on Duthomhas' words...

int total[INT_MAX]

Assuming INT_MAX to be 2147483647, an array of 2147483647 int values would take up 2147483647 * 4 = 8589934588 bytes, which is about 8.5 GB

The stack typically has a few MB of memory available, so there's no way this could go on the stack. Even putting that on the heap would tax some systems.

Some systems have ints of size 8 bytes rather than 4 bytes; if INT_MAX is the same and an int consumes 8 bytes rather than 4, this array would need 17 GB of memory.

How much memory does your system have? Do you really need an array that takes up 8.5GB?



Last edited on
Thank you very much
Hi,
I tested out the program and it works fine. Thank you very much for your help. I realized that my system only have a RAM of 8 GB, causing my previous program to crash. Thank you very much for both of your help.
Topic archived. No new replies allowed.