Sort the array using pointers

C program to sort the array using pointers.

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50

void print_array(int arr[], int n);

void main()
{
	int arr[MAX];
    int n, i, j, temp;
    int *ptr;

    printf("Enter the size of the array\t:");
    scanf("%d",&n);

    printf("\nEnter elements in the array\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }

    ptr = arr;

    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(*(ptr+i) > *(ptr+j))
            {
                temp = *(ptr+i);
                *(ptr+i) = *(ptr+j);
                *(ptr+j) = temp;
            }
        }
    }

    printf("\nElements in ascending order \t:");
    print_array(arr, n);

    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(*(ptr+i) < *(ptr+j))
            {
                temp = *(ptr+i);
                *(ptr+i) = *(ptr+j);
                *(ptr+j) = temp;
            }
        }
    }

    printf("\nElements in descending order \t:");
    print_array(arr, n);

    getch();
}

void print_array(int *arr, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("%d ",arr[i]);
    }
}

Output

Enter the size of the array     :5

Enter elements in the array
4
3
7
2
1

Elements in ascending order     :1 2 3 4 7
Elements in descending order    :7 4 3 2 1

Explanation

In the above program, an integer array 'arr' is declared and a pointer variable 'ptr' is also declared. Number of elements 'n' is taken as an input from the user and then 'n' elements are also entered.
ptr = arr, ptr points to arr[0] element of the array.
Logic for bubble sort is applied to sort the array.
Values of the array are accessed using *(ptr+i)
*(ptr+i) is equivalent to the arr[i] element.