C Program to Sort an Array using a Pointer

Write a C program to sort an array using a pointer. This c example passes the pointer to the SortArray function and uses the temp variable inside the for loop to sort the array in ascending order.

#include <stdio.h>

void SortArray(int Size, int* parr)
{
	int i, j, temp;	

	for (i = 0; i < Size; i++)
	{
		for (j = i + 1; j < Size; j++)
		{
			if(*(parr + j) < *(parr + i))
			{
				temp = *(parr + i);
				*(parr + i) = *(parr + j);
				*(parr + j) = temp;
			}			
		}
	}
	printf("\nSorted Array Elements using Pointer = ");
	for(i = 0; i < Size; i++)
	{
		printf("%d  ", *(parr + i));
	}	
}

int main()
{
	int Size;

	printf("\nEnter Array Size to Sort using Pointers = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("\nPlease Enter %d elements of an Array = ", Size);
	for (int i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
    }  	
	SortArray(Size, arr);   
	printf("\n");	
}
C Program to Sort an Array using a Pointer

This c program will sort the given array in ascending order by passing the array pointer to functions and the while loop for sorting.

#include <stdio.h>

void SortArray(int Size, int *parr)
{
	int i, j, temp;
	i = 0;

	while (i < Size)
	{
		j = i + 1;
		while (j < Size)
		{
			if (*(parr + j) < *(parr + i))
			{
				temp = *(parr + i);
				*(parr + i) = *(parr + j);
				*(parr + j) = temp;
			}
			j++;
		}
		i++;
	}
	printf("\nSorted Array Elements using Pointer = ");
	i = 0;
	while (i < Size)
	{
		printf("%d  ", *(parr + i));
		i++;
	}
}
void acceptArrayItems(int Size, int *parr)
{
	printf("\nPlease Enter %d elements of an Array = ", Size);

	int i = 0;
	while (i < Size)
	{
		scanf("%d", parr + i);
		i++;
	}
}
int main()
{
	int Size;

	printf("\nEnter Array Size to Sort using Pointers = ");
	scanf("%d", &Size);

	int arr[Size];
	acceptArrayItems(Size, arr);

	SortArray(Size, arr);
	printf("\n");
}
Enter Array Size to Sort using Pointers = 9

Please Enter 9 elements of an Array = 11 99 33 234 17 98 5 55 49

Sorted Array Elements using Pointer = 5  11  17  33  49  55  98  99  234  

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.