← All resources

Write a program to illustrate the use of Malloc Function in C and sort an array in ascending order using a function Bubble

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void bubble(int *p, int n)
{
	int i, j, tmp;
	for(i=0;i<n;i++)
	{
		for(j=0;j<n-1-i;j++)
		{
			if(*(p+j)>*(p+j+1))
			{
				tmp = *(p+j);
				*(p+j) = *(p+j+1);
				*(p+j+1) = tmp;
			}
		}
	}
}
void main()
{
	int *p, i, j, tmp, n;
	clrscr();
	printf("nEnter the size of the array:");
	scanf("%d", &n);
	p = (int*)malloc(n*sizeof(int));
	printf("nEnter the values for the array:");
	for(i=0;i<n;i++)
	{
		scanf("%d", (p+i));
	}
	bubble(p, n);
	printf("nSorted Values are:");
	for(i=0;i<n;i++)
	{
		printf("n%d", *(p+i));
	}
	getch();
}