Sort an integer array in ascending order with bubble sort, accessing the elements only through pointers.
Solution
main.c
#include <stdio.h>
void sort(int *a, int n) {
for (int i = 0; i < n - 1; i++)
for (int *p = a; p < a + n - 1 - i; p++)
if (*p > *(p + 1)) {
int t = *p;
*p = *(p + 1);
*(p + 1) = t;
}
}
int main(void) {
int a[] = {42, 7, 19, 3, 25};
int n = sizeof a / sizeof a[0];
sort(a, n);
for (int *p = a; p < a + n; p++)
printf("%d ", *p);
printf("\n");
return 0;
}
Output Verified by compiling and running
3 7 19 25 42
After pass i the largest i + 1 values are already at the end, so the inner pointer stops at a + n - 1 - i. Neighbours *p and *(p + 1) are swapped when they are out of order.
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!