C++ swapping problem

Hello, i have a problem that ask me to swap the even index(elements) with odd index(elements),but it doesnt work can someone help me please.Thanks from now.

1
2
3
4
5
6
7
8
9
10
void swap(int a[]){
	int temp,i;
	for(i=2;i>10;i++){
	
		if(i%2==0){
			temp = a[i];
			a[i] = a[++i];
			a[i] = temp;		
		}
	}
You can omit the if on line 5 due to i++ and ++i.

The problem is line 3: i>10 change to i<10

Line 7 is a problem because of the order of evaluation. If ++i is evaluated first and then the value is assigned the value will not be changed. Better this:
1
2
3
4
			int temp = a[i];
			a[i] = a[i + 1];
			a[i + 1] = temp;
			++i; // Put ++i here 
Last edited on
do you need the %2?

for(I = 2; I < 10; I+=2) //2&3 swap, 4&5 swap, ... is this what you need?
//what about 0&1?
{
tmp = a[I];
a[I] = a[I+1];
a[I+1] = tmp;

}

note that this assumes an odd input array size, if your array is size 10 it will crash on swapping 10&11


Last edited on
A more fundamental problem is here: void swap(int a[])

even though a appears to be defined as an array, the declaration is "adjusted" to a pointer to the element type,
http://stackoverflow.com/questions/31346940/passing-array-as-function-parameter-in-c

try something like this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <utility>

void swapEvenOdd(int a[], const size_t n)
{
    if (n%2)
    {
        for (auto i = 0; i < n - 1; i += 2 )
        {
            std::swap (a[i], a[i+1]);
        }
    }
    else
    {
        for (auto i = 0; i < n; i += 2 )
        {
            std::swap (a[i], a[i+1]);
        }
    }
    for (auto i = 0; i <n; ++i)std::cout << a[i] << " ";
}

int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    swapEvenOdd(a, sizeof(a)/sizeof(a[0]));

    std::cout << "\n";

    int b[] = {1, 2, 3, 4, 5, 6, 7};
    swapEvenOdd(b, sizeof(b)/sizeof(b[0]));
}


Last edited on
Topic archived. No new replies allowed.