Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
- reverse function : is used to reverse the array through pointers
- swap function : is used to swap two memory contents
- print function : will print the array
Approach : In reverse function we take two pointers one pointing at the beginning of the array, other pointing at end of the array. The contents of the memory location pointed by these two pointers are swapped and then the value of first pointer is increased and that of second pointer is decreased . Examples:
Input : array = 2, 4, -6, 5, 8, -1
Output : reverse_array = -1, 8, 5, -6, 4, 2
Input : array = 1, 4, -6, 8, -10, -12
Output : reverse_array = -12, -10, 8, -6, 4, 1
Implementation:
C++
#include <iostream>
using namespace std;
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void reverse( int array[], int array_size)
{
int *pointer1 = array,
*pointer2 = array + array_size - 1;
while (pointer1 < pointer2) {
swap(pointer1, pointer2);
pointer1++;
pointer2--;
}
}
void print( int * array, int array_size)
{
int *length = array + array_size,
*position = array;
cout << "Array = " ;
for (position = array; position < length; position++)
cout << *position << " " ;
}
int main()
{
int array[] = { 2, 4, -6, 5, 8, -1 };
cout << "Original " ;
print(array, 6);
cout << "Reverse " ;
reverse(array, 6);
print(array, 6);
return 0;
}
|
C
#include <stdio.h>
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void reverse( int array[], int array_size)
{
int *pointer1 = array,
*pointer2 = array + array_size - 1;
while (pointer1 < pointer2) {
swap(pointer1, pointer2);
pointer1++;
pointer2--;
}
}
void print( int * array, int array_size)
{
int *length = array + array_size,
*position = array;
printf ( "Array = " );
for (position = array; position < length; position++)
printf ( "%d " , *position);
}
int main()
{
int array[] = { 2, 4, -6, 5, 8, -1 };
printf ( "Original " );
print(array, 6);
printf ( "Reverse " );
reverse(array, 6);
print(array, 6);
return 0;
}
|
Output
Original Array = 2 4 -6 5 8 -1 Reverse Array = -1 8 5 -6 4 2
Time Complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
13 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...