Program to sort elements in an array – I ran it using an online IDE, but the code won’t work for 4 elements. I tried different values, but it simply won’t give the output.
int main()
{
int el = 0, num = 0;
cout << "Enter the number of elements in an array:" << endl;
cin >> el;
int a[el];
cout << "ENTER ELEMENTS:" << endl;
for (int i = 0; i < el; i++)
cin >> a[i];
for (int j = 0; j < el; j++)
{
for (int i = 0; i < el; i++)
{
if (a[i] > a[i+1])
{
num = a[i + 1];
a[i + 1] = a[i];
a[i] = num;
}
}
}
for (int i = 0; i < el; i++)
{
cout << a[i];
cout << endl;
}
return 0;
}
>Solution :
As someone has already mentioned, int a[el] is not standard C++ unless el is a constant value, known at compile time. You should specify the maximum number of elements by a constant, or you can check std::vector if you want to provide the size of the array at runtime.
As for the question, the bug is here:
for (int j = 0; j < el; j++) {
for (int i = 0; i < el; i++) {
if (a[i] > a[i + 1]) {
// ... the rest of the code
}
}
}
When i = el - 1, the expression a[i + 1] tries to access unitialised memory, which is undefined behaviour. Change this second for to this
for (int i = 1; i < el; i++) {
if (a[i - 1] > a[i]) {
// the rest of the code
}
}
and everything should be fine (just keep in mind to change the code using i as well!).