Reverse an integer array in place using two pointers, one from each end.
Solution
main.c
#include <stdio.h>
void reverse(int *a, int n) {
int *left = a, *right = a + n - 1;
while (left < right) {
int t = *left;
*left++ = *right;
*right-- = t;
}
}
int main(void) {
int a[] = {1, 2, 3, 4, 5, 6};
int n = sizeof a / sizeof a[0];
reverse(a, n);
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Output Verified by compiling and running
6 5 4 3 2 1
Swap the elements at the two pointers, then move them towards each other until they meet: n/2 swaps, no second array. *left++ = *right stores, then moves left forward.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!