LearnFrenzy
Sign in Take a free test

Pointers · Pointer Programs · Question 5

C program to sort an array using pointers (bubble sort) Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Popular