Skip to content
Related Articles

Related Articles

C program to sort an array using pointers
  • Difficulty Level : Easy
  • Last Updated : 30 Jul, 2019

Given an array of size n, the task is to sort this array using pointers in C.

Examples:

Input: n = 5, arr[] = {0, 23, 14, 12, 9}
Output: {0, 9, 12, 14, 23}

Input: n = 3, arr[] = {7, 0, 2}
Output: {0, 2, 7}

Approach: The array can be fetched with the help of pointers with the pointer variable pointing to the base address of the array. Hence in order to sort the array using pointers, we need to access the elements of the array using (pointer + index) format.

Below is the implementation of the above approach:



Program:




#include <stdio.h>
  
// Function to sort the numbers using pointers
void sort(int n, int* ptr)
{
    int i, j, t;
  
    // Sort the numbers using pointers
    for (i = 0; i < n; i++) {
  
        for (j = i + 1; j < n; j++) {
  
            if (*(ptr + j) < *(ptr + i)) {
  
                t = *(ptr + i);
                *(ptr + i) = *(ptr + j);
                *(ptr + j) = t;
            }
        }
    }
  
    // print the numbers
    for (i = 0; i < n; i++)
        printf("%d ", *(ptr + i));
}
  
// Driver code
int main()
{
    int n = 5;
    int arr[] = { 0, 23, 14, 12, 9 };
  
    sort(n, arr);
  
    return 0;
}


Output:

0 9 12 14 23

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :