2

I'm asking for help with a problem implying an array sorting in the following manner: all even numbers must be in front of the odd ones. I've partially made the problem, but I did the sorting in the opposite manner and I can not manage to fix it.

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    int v[100], n, i, aux = 0, inv;
    cout << "Number of elements: ";
    cin >> n;
    for (i = 0; i < n; i++)
    {
        cout << "v[" << i << "]=";
        cin >> v[i];
    }

    do
    {   
        inv = 0;
        for (i = 0; i < n; i++)
        {
            if (v[i] % 2 == 1 && v[i + 1] % 2 == 0)
            {
                inv = 1;
                aux = v[i];
                v[i] = v[i + 1];
                v[i + 1] = aux;
            }
        }
    } while (inv != 0);
    cout << endl;

    for (i = 0; i < n; i++)
        cout << v[i] << " ";
    cout << endl;
    system("pause");
    return 0;
}

The output for this would be:

n = 8
1 3 2 4 7 8 4 2

Result: 2 4 8 4 2 -858993460 1 3
2
  • This seems like a good time to learn how to debug your programs. Commented Oct 22, 2018 at 9:09
  • Alright. I've checked on my program, but my guess is that, because of the size of the array, [100], the free spaces would get the value `-858993460'. I'm not so common with the dynamic alloc. of memory, so is there any possibility I can initialize the array with no number of elements and give it the number while inputing the values for its elements? Or any tips of dynamic alloc.? Commented Oct 22, 2018 at 9:15

1 Answer 1

1

In the expression v[i + 1], you access v[n] when i = n - 1, this will result in an out-of-bounds memory access which results in undefined behaviour. You should change the for loop to this:

for (i = 0; i < n - 1; i++)

The output for the given input is:

a.exe
Number of elements: 8
v[0]=1
v[1]=3
v[2]=2
v[3]=4
v[4]=7
v[5]=8
v[6]=4
v[7]=2

2 4 8 4 2 1 3 7
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, that's right! I forgot that I'm checking, simultaneously, the first element and the next one. Yeah, you are right. Thank you!
I'm aware of that, but the portal won't let me accept before 5 minutes, I'm afraid. I appreciate the answer. I have, still, a question about the program's efficiency (or complexity), if I'm speaking correctly?
You can use stl algorithms for swapping, iterating over elements etc. These are considered very efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.