'Code not working trying to do bubble sort in different way [closed]

#include <iostream>

using namespace std;

int main() {
  int n, arr[n];
  cin >> n;
  int i, j;
  int counter = 1;
  for (i = 0; i < n; i++) {
    cin >> arr[i]; // taking arr inputs
  }
  while (counter < n) { 
    for (i = 0; i < n - counter; i++) {
      if (arr[i] > arr[i + 1]) {
        j = arr[i]; // swapping numbers
        arr[i] = arr[i + 1];
        arr[i + 1] = j;
      }
    }
    counter++;
  }
}

my code is simply exiting it isnt taking any inputs or giving any outputs or errors. i just want to do it this way lemme know what are the mistakes dont change the method

I tried changing conter into loop but it didnt work

tryin bubble sort



Solution 1:[1]

We beginners need to hold together.

There are some very minor problems in your code.

Your variable "n" is uninitialized. So it has an indeterminate value. So, something. Then you try to set the size of your array with this "something". And after that, you read the size from the user.

Additionally. VLA (Variable length Arrays), so something like "array[n]", with "n" not being a compile time constant is illegal. It is not part of C++. Some compiler are allowing it as an extension, but it is illegal C++ code. But the good message is: There is a drop in replacement: The std::vector

And last but not least, if you want to see some output, then you need to output something. So, for example with "std::cout << something".

With above changes, your code coul look like:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n = 0;
    cin >> n;
    std::vector<int> arr(n);
    int i = 0, j = 0;
    int counter = 1;
    for (i = 0; i < n; i++) {
        cin >> arr[i]; // taking arr inputs
    }
    while (counter < n) {
        for (i = 0; i < n - counter; i++) {
            if (arr[i] > arr[i + 1]) {
                j = arr[i]; // swapping numbers
                arr[i] = arr[i + 1];
                arr[i + 1] = j;
            }
        }
        counter++;
    }
    for (int k : arr) std::cout << k << ' ';
}

Still not perfect, but OK for the beginning.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Armin Montigny