#include <iostream>
#include <algorithm>
usingnamespace 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);
}
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.