Open In App

C program to sort an array using pointers

Improve
Improve
Like Article
Like
Save
Share
Report

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:  

C




#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

Time Complexity: O(n2), where n represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.


Last Updated : 26 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads