Home > Software engineering >  Bubble sort refuses to run in application compilers, but runs on online compilers
Bubble sort refuses to run in application compilers, but runs on online compilers

Time:11-30

So this is the code I wrote for bubble sorting a user defined list. It crashes (brings the error, 'main.exe has stopped working') when I use apps like DevC , CodeBlocks and VSCode to run. but when I use a web compiler, it works perfectly. (The apps only crash while running this code. They are able to run other pieces of code smoothly)

int main()
{
    int n;
    int numbers[n];
    cout << "How many numbers do you want to sort?\n";
    cin >> n;
    cout << "Enter the "<< n <<" values.\n";
    for (int w = 0; w < n; w  )
    {
        cin >> numbers[w];
    }

    cout << "The unsorted list is: \n";
    for (int m = 0; m < n; m  )
    {
        cout << numbers[m] << "\t";
    }
    for (int iterat = 0; iterat < n-1; iterat  )
        {
            for (int j = 0; j < n-1; j  )
            {
                if (numbers[j] > numbers[j   1])
                {
                    int temp = numbers[j];
                    numbers[j] = numbers[j   1];
                    numbers[j   1] = temp;
                }
            }
        }

    cout << "The sorted list is: \n";
    for (int p = 0; p < n; p  )
    {
        cout << numbers[p] << "\t";
    }

}

I'm a student and we're currently learning sorting algorithms so I've asked my lecturer and multiple classmates for their help, but they're all stumped on what the problem could be because this should be correct. Please advice me on what be the problem might be and how to fix it.

CodePudding user response:

Problem is numbers[n] with un initialised value of n. It takes some garbage value of n and tries to allocate space. It may work sometime and may fail sometime depending on what is the garbage value its taking.

If the garbage value of n is negative or too large, it will fail. Move array declaration after initialisation of n.

  • Related