Skip to content
Home » C Program to Sort List of Array Elements Using Function & Pointer

C Program to Sort List of Array Elements Using Function & Pointer

Learn about C Program to Sort List of Array Elements Using Function & Pointer in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

C Program to Sort List of Array Elements Using Function & Pointer

The array can be retrieved using pointers, with the pointer variable referring to the array’s base address. Hence sorting of elements in array could be performed using below code:

#include<stdio.h>
void sort(int *x);
int main()
{
  int a[5], i;
  int *pa;
  pa =  &a[0];
  printf("Enter array elements: ");
  for(i=0;i<5;i++)
  {
    scanf("%d",pa+i);
  }
  sort( &a[0] );
  printf("Sorted array is: ");
  for(i=0;i<5;i++)
  {
    printf("%d\t", *(pa+i));
  }
  return 0;
}

void sort(int *x)
{
  int i, j, temp;
  for(i=0;i<5;i++)
  {
    for(j=i+1;j<5;j++)
    {
      if( *(x+i) > *(x+j) )
      {
        temp = *(x+i);
        *(x+i) = *(x+j);
        *(x+j) = temp;
      }
    }
  }
}

Output:

Enter array elements: 34
67
45
4
56
Sorted array is: 4 34 45 56 67

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
Find Sum and Average of an Array Using the Pointer in C
Read and write an array using function and pointer