Wednesday, 6 November 2013

[C programming] Reverse an array in place (Do not use additional array)

Reverse an array in-place i.e you cannot use any additional array or
in other words, space complexity of the solution should be O(1)

#include<stdio.h>
#include<stdlib.h>

void main()
{
int size, i, temp;
int *array;

printf("Enter size of an array:\n");
scanf("%d", &size);

array = (int*)malloc(sizeof(int) * size);

printf("Enter %d elements\n", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);

printf("List elements are..\n");
for (i = 0; i < size; i++)
printf("%d\n", array[i]);

for (i = 0; i <= (size - 1) / 2; i++) {
temp = array[i];
array[i] = array[size-1-i];
array[size-1-i] = temp;
}

printf("After Reversing the list,  elements are..\n");
for (i = 0; i < size; i++)
printf("%d\n", array[i]);
}

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...