Pointer Assignment 18 — Sort an Array Using a Function and Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Sort an Array Using a Function and Pointers — Pointer-Based Bubble Sort in Place

📑 On this page:
  • How Pointer-Based Sorting Works
  • The Three Steps of the Sort
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to pass an array to a sorting function as a pointer
  • How two nested pointers express the comparison and swap steps of bubble sort
  • Why *(p + 1) is how a pointer "looks at the next element"
  • How the unsorted region shrinks after each pass
  • How to add an early-exit optimization when the array is already sorted

How Pointer-Based Sorting Works

Sorting an array means rearranging its elements into a specific order — usually ascending. There are many algorithms, and bubble sort is the simplest to write with pointers because it does nothing but compare and swap adjacent elements. The core idea is: walk the array comparing each element with its neighbour; if they're out of order, swap them. One full pass pushes the largest element to the end. Repeat with one fewer element each time, and the array is sorted.

Doing this with pointers instead of indices means there are no i and j variables. Instead, an outer pointer (let's call it i) marks the boundary of the unsorted region, and an inner pointer (p) walks from the start of the array to the boundary, comparing *p with *(p + 1). The expression *(p + 1) is the pointer way to say "the element after the one p points to." A swap exchanges the values through those pointers, so the array itself changes — no new array is allocated.

The function receives the array as a pointer because C arrays decay to pointers when passed to functions. Inside the function, arr is an int *, and arr + n is one past the last element. The pointer arithmetic p < arr + n - pass expresses "the inner loop runs over the unsorted region only" — the same effect as the index version j < n - 1 - pass. The pointer version is arguably clearer about what is being iterated: the region between arr and a shrinking end pointer.

💡 In one line: An outer pointer marks the pass, an inner pointer compares adjacent elements, and a swap through pointers puts them in order — n-1 passes and the array is sorted.

Diagram of two pointers walking an array during bubble sort, comparing adjacent elements and swapping them when out of order

The Three Steps of the Sort

Step Pointer operation Effect
1. Run the passesfor (int *i = arr; i < arr + n - 1; i++)Each pass fixes one more element at the end
2. Compare adjacent elementsfor (int *p = arr; p < arr + n - 1 - pass; p++) { if (*p > *(p + 1)) swap(p, p + 1); }Larger elements bubble toward the end of the unsorted region
3. Done—After n-1 passes, the entire array is sorted in place

Why does bubble sort work? Each inner pass compares every adjacent pair in the unsorted region and swaps them if they're out of order. After the first pass, the largest element has been compared against every other element and has "bubbled" to the last position — so the last element is now in its final place. After the second pass, the second-largest element is in its final place, and so on. After n-1 passes, every element is in its final place. The last pass doesn't need to compare the last two elements of a region of size 1, which is why the inner loop's bound shrinks by one each pass.

The swap itself is the key pointer operation. You can't swap two elements without a temporary, and you can't swap through *p and *(p + 1) unless you use a temporary. The standard three-line swap is int t = *p; *p = *(p + 1); *(p + 1) = t;. After this, the two elements have exchanged values, and both pointers still point at the same positions — only the values at those positions have changed. This is why the sort is in-place: the pointers move, but the array does not.

Complete C Program

Program: sort an array using a function and pointers (bubble sort, ascending)

#include <stdio.h>

#define MAX 100

/* Swap the two integers that a and b point at. */
static void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

/* Sort arr in place using bubble sort and pointers.
   arr is a pointer to the first element; n is the count. */
void sort_array(int *arr, int n) {
    if (arr == NULL || n < 2) {
        return;  /* nothing to sort */
    }

    int *end = arr + n;              /* one past the last element */

    for (int *i = arr; i < end - 1; i++) {
        int swapped = 0;

        /* Walk the unsorted region, comparing neighbours. */
        for (int *p = arr; p < end - 1 - (i - arr); p++) {
            if (*p > *(p + 1)) {
                swap(p, p + 1);
                swapped = 1;
            }
        }

        if (!swapped) {
            break;  /* already sorted — stop early */
        }
    }
}

/* Print the array by walking a pointer. */
void print_array(const int *arr, int n) {
    const int *p = arr;
    const int *end = arr + n;
    while (p < end) {
        printf("%d ", *p);
        p++;
    }
    printf("\n");
}

int main(void) {
    int arr[MAX];
    int n, i;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
        printf("Invalid size.\n");
        return 1;
    }

    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) {
            printf("Invalid input.\n");
            return 1;
        }
    }

    printf("\nBefore sorting: ");
    print_array(arr, n);

    sort_array(arr, n);

    printf("After sorting : ");
    print_array(arr, n);

    return 0;
}
                                    

Program Output

How many elements? 6
Enter 6 integers:
42 17 93 8 55 23

Before sorting: 42 17 93 8 55 23
After sorting : 8 17 23 42 55 93
                                

A second run, with input that is already sorted:

How many elements? 5
Enter 5 integers:
1 2 3 4 5

Before sorting: 1 2 3 4 5
After sorting : 1 2 3 4 5
                                

In the first run, the array is shuffled and the function sorts it into ascending order. In the second run, the array is already sorted, and the early-exit optimization kicks in: after the first pass, swapped is still 0, so the function breaks immediately and returns without further passes. That's a small but real performance improvement for nearly-sorted input, and it's a common interview point.

Step-by-Step Explanation

Let's trace the pointer mechanics carefully.

1. The swap helper

swap(int *a, int *b) takes two pointers and exchanges the values they point at. It has to use a temporary: int t = *a; *a = *b; *b = t;. Without the temporary, the first assignment would overwrite the value that the second assignment needs. This is a classic and it's worth getting exactly right, because the same helper is reused in many sorting algorithms — selection sort, quicksort's partition, heap sort's sift-down — so it's a building block.

2. The function signature and guards

sort_array(int *arr, int n) receives a pointer and a count. The guard if (arr == NULL || n < 2) return; handles the trivial cases: a null pointer (nothing to sort), an empty array (n = 0), and a single element (n = 1). Without this guard, the loops would still be correct in most cases, but end - 1 for n = 0 would be arr - 1, which is technically forming a pointer before the start of the array — undefined. The guard avoids the question entirely.

3. The end pointer

int *end = arr + n; is one past the last element. It's used throughout the loops as the upper bound. The expression end - 1 is the last real element — that's the position the largest element will bubble to on the first pass. Using a precomputed end rather than writing arr + n every time makes the loops read a little more cleanly and avoids re-computing the same expression.

4. The outer loop

for (int *i = arr; i < end - 1; i++) runs n - 1 times. Each iteration is one "pass" of bubble sort. The pointer i itself isn't used for indexing inside the loop — it's just counting passes. It could have been an integer pass, and the code would be the same. The pointer choice here is a style decision; some programmers prefer an int counter for passes because it reads more naturally, and use pointers only for the inner comparison and swap. Either is fine.

5. The inner loop

for (int *p = arr; p < end - 1 - (i - arr); p++) is the interesting one. The bound end - 1 - (i - arr) shrinks by one each pass. Here's why: on the first pass, the largest element bubbles to the last position, so the last position is fixed. On the second pass, the second-largest bubbles to the second-to-last position, which is now fixed. The inner loop only needs to compare up to the last unsorted position, which is one earlier each pass.

The expression i - arr is the pass number (0 on the first pass, 1 on the second, and so on). Subtracting it from end - 1 moves the bound one element to the left each pass. You could also track the pass number as an integer and write p < end - 1 - pass; the result is identical. The pointer form is slightly more verbose, but it avoids mixing an int counter with pointer arithmetic.

6. The comparison and swap

if (*p > *(p + 1)) compares the element at p with its neighbour. If the left one is bigger, they're out of order and need to be swapped. swap(p, p + 1) passes the two pointers to the helper, which exchanges the values. Note that we don't pass *p and *(p + 1) — those would pass the values, not the addresses, and the helper couldn't modify the array. This is the single most important distinction in pointer-based sorting: the function needs pointers, not values.

7. Tracing one pass

Take the array [42, 17, 93, 8, 55, 23] and the first pass:

  • p at 42: 42 > 17 → swap → [17, 42, 93, 8, 55, 23]. p advances.
  • p at 42: 42 > 93? No → no swap. p advances.
  • p at 93: 93 > 8 → swap → [17, 42, 8, 93, 55, 23]. p advances.
  • p at 93: 93 > 55 → swap → [17, 42, 8, 55, 93, 23]. p advances.
  • p at 93: 93 > 23 → swap → [17, 42, 8, 55, 23, 93]. p advances past the bound.

After the first pass, the largest element, 93, has reached the last position. That position is now fixed, and the second pass runs with a bound one element earlier. The same logic repeats, and after five passes the whole array is sorted. In the actual program, the early-exit check if (!swapped) break; would stop earlier if the array became sorted before the fifth pass.

8. The early-exit optimization

int swapped = 0; is set at the start of each pass, and any swap inside the inner loop sets it to 1. If a full pass finishes with swapped == 0, no swaps were made, meaning the array is already sorted — and bubble sort breaks out. This makes the best case O(n) for an already-sorted array, instead of the naive O(n²). It's a small change that costs almost nothing and improves real-world performance noticeably on partially sorted data.

9. Printing with a pointer walk

print_array(const int *arr, int n) walks a pointer from arr to arr + n, printing each element. The const on arr means the function promises not to modify the array, which is correct — it only reads. Using a pointer walk instead of arr[i] isn't required (both are fine), but it matches the pointer-based style of the rest of the program and demonstrates the same idiom used in sorting.

10. Why the array is sorted in place

The function has no return value for the sorted array — it returns void — and it doesn't allocate a new array. It modifies the caller's array through the pointer it was given. This is the standard C convention for "sort in place": the caller passes an array, the function rearranges its contents, and the caller sees the result through its own array variable. It's why the program prints arr after the call — the sorted data is already in arr.

11. Pointer vs index version

Here's the same algorithm with indices, for comparison:

void sort_array_index(int arr[], int n) {
    for (int pass = 0; pass < n - 1; pass++) {
        int swapped = 0;
        for (int j = 0; j < n - 1 - pass; j++) {
            if (arr[j] > arr[j + 1]) {
                int t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
}
                                

Both versions produce the same result and have the same complexity. The pointer version uses *(p + 1) where the index version uses arr[j + 1] — but arr[j + 1] is defined as *(arr + j + 1), so the two are literally the same operation under the hood. The choice is a matter of style: some programmers find the index version more readable for nested loops, others prefer the pointer version because the loops walk the actual range [arr, end).

12. Complexity and alternatives

Bubble sort is O(n²) in the worst and average cases, and O(n) in the best case (with the early-exit check). It's not the fastest sorting algorithm — quicksort is O(n log n) on average, merge sort is O(n log n) in all cases — but it's the easiest to explain and to implement correctly with pointers, which is why it's the standard exercise. Once you understand this pointer version, the same skills transfer directly to selection sort, insertion sort, and even quicksort's partition step, all of which walk pointers through the array and swap elements in place.

🎯 Remember this: Bubble sort with pointers is two nested pointer walks and a swap. The outer pointer counts passes, the inner pointer compares *p with *(p + 1), and the swap helper exchanges values through pointers. The array is modified in place — no new allocation, no return value.

Frequently Asked Questions

1. Why does the sort function return void instead of the sorted array?

Because the function modifies the array in place. When you pass an array to a function in C, it's passed as a pointer to its first element, so the function can change the elements and the caller sees the changes. There's no need to return the array — returning a pointer would just return the same address the caller already has. void correctly expresses "the function has a side effect on the array, and that's the entire result."

2. Why is the inner bound end - 1 - (i - arr)?

Each pass of bubble sort fixes one more element at the end of the array. After the first pass, the last element is in its final place; after the second, the last two are; and so on. So the inner loop only needs to compare up to the last unsorted position, which moves one element left each pass. end - 1 is the last element, and i - arr is the pass number (0, 1, 2, ...). Subtracting the pass number from end - 1 moves the bound left by one each pass. It's the pointer equivalent of j < n - 1 - pass in the index version.

3. Why do we call swap(p, p + 1) instead of swap(*p, *(p + 1))?

Because swap needs to modify the array, and modifying requires addresses. If you pass *p and *(p + 1), you're passing the values — the helper would swap its local copies and the original array would be unchanged. Passing p and p + 1 passes pointers, and the helper can dereference them and change the actual array elements. This is the same rule as for scanf: pass addresses, not values.

4. What is the swapped flag for?

It's an early-exit optimization. If a full pass completes without making any swaps, the array is already sorted and no further passes are needed. Without the flag, the algorithm would still do all n - 1 passes even on a sorted array. With the flag, the best case becomes O(n) instead of O(n²) — a significant improvement for nearly-sorted input. It's a small addition that costs almost nothing and is expected in any serious implementation.

5. Why use bubble sort when quicksort is faster?

Bubble sort is the simplest sorting algorithm to write and to reason about, which makes it the standard teaching example. Quicksort is faster in practice (O(n log n) on average vs O(n²)), but it's more complex — the partition step is subtle, and pointer bugs in quicksort are notoriously hard to debug. For this exercise, the goal is to demonstrate pointer arithmetic and swaps, and bubble sort does that with the fewest moving parts. Once you're comfortable with the pointer patterns here, moving to quicksort or merge sort is a natural next step.

6. Can I sort in descending order?

Yes. Change the comparison in the inner loop from if (*p > *(p + 1)) to if (*p < *(p + 1)). The rest of the algorithm is identical: elements that are out of order (smaller before larger, in this case) are swapped, and the larger elements bubble to the front. A more general solution would take a comparison function as a parameter, which is how qsort works — that's a good exercise once the basic version is working.

💡 Tip: Once this works, try implementing selection sort with pointers: find the minimum element in the unsorted region using a pointer walk, then swap it with the first element of the region. The pointer patterns are very similar, and comparing the two algorithms side by side is a great way to understand both.

📖 Related Tutorials

  • 9. Linear Search in an Array Using Pointers
  • 16. Binary Search in an Array Using Pointers
  • 9. Reverse a String Using Pointers
  • 8. Copy One String to Another Using Pointers
  • The Pointer to an Array
  • All 30 Pointer Assignments

Previous Topic: -->> 16. Binary Search in an Array Using Pointers   ||   Next Topic: -->> Reverse a String Using Pointers


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.