Reverse an array elements

I don't understand why size is divided by 2 for the second function ?



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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <algorithm>
using namespace std;

void example1 ( int array[], int size){

	if (size < 0){
		cout << "Warning! Size is less than 0! " << endl;
		exit(0);
	}
	cout << "Regular array elements: ";
	for (int i = 0; i < size; i++){
		int *p = &array[i];
		cout << *p << " ";
	}

	// Reversing the output using the for loop.
	// Note: The elements in the array are not reversed.
	cout << "\n" << "Reversed array elements: ";
	for (int i = 1; i <= size; i++){
		int *p = &array[size - i];
		cout << *p << " ";
	}
}


void example2 ( int array[], int size){
	if (size < 0){
		cout << "Warning! Size is less than 0! " << endl;
		exit(0);
	}
	cout << endl << endl;

   // Why divide size by 2 ?
    int temp;
    for (int i = 0; i < size/2; i++){
      temp = array[i];
      array[i] = array[size-i-1];
      array[size-i-1] = temp;
    }
    
    cout << "Reversed array using temp variable is: ";
    for (int i = 0 ; i < size; i++){
        cout << array[i] << " ";
    }
}
int main(){
	int array[] = {1, 2, 3, 4, 5};
	int size = sizeof(array)/sizeof(int);
	example1(array, size);
	example2(array, size);
}
To reverse abcde (size:5)
Swap first and last: ebcda
Swap second and second last: edcba
That's it; we have done swapping size/2 (2) times.
Oh so you mean because we divide the size by 2 just because we have two swapping ? or is it because there are two elements of the array being swapped at the same time ?

The positions of two elements are interchanged in each swap.
Where n is the size of the sequence, we swap n/2 times.
If n is even (say 100), we swap n/2 (50) times (in all moving 100 characters)
If n is odd (say 101), we swap n/2 (50) times (leaving the middle character unchanged)

To reverse abcdef (size:6)
Swap first and last: fbcdea
Swap second and second last: fecdba
Swap third and third last: fedcba
That's it; we have done swapping size/2 (3) times.
Interesting. I have never been in a situation to use size/2 for reversing an array, so I was surprised by both the syntax and logic of size/2.

Thanks for clarification.
Topic archived. No new replies allowed.