Angel
Angel

Reputation: 35

Sorting an array— issue

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

Upvotes: 2

Views: 53

Answers (1)

P.W
P.W

Reputation: 26800

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

Upvotes: 1

Related Questions