Thursday, November 27, 2014

C program to sort elements in an array using bubble sort with pointers and use it in main program.

/*...................................................................................................................................................
File Name: rec21.c
Program :   program to sort elements in an array using bubble sort
with pointers and use it in main program.
Author : sujithbaby440@gmail.com
Date : 21-11-2014
...................................................................................................................................................*/
#include<stdio.h>
#include<malloc.h>
void fnInputArray(int N,int *s);
void fnDisplayArray(int N,int *s);
void fnBubbleSort(int N,int *s);
main()
{
int N,*s;
system("clear");
printf("Program to sort elements in an array using buuble sort\n");
printf("Enter the size of an array\n");
scanf("%d",&N);
s=(int*)malloc((N+1)*sizeof(int));
printf("Enter the %d elements in an array:\n",N);
fnInputArray(N,s);
printf("The elements in an array are:\n");
fnDisplayArray(N,s);
fnBubbleSort(N,s);
printf("\nThe elements in an after sorting are:\n");
fnDisplayArray(N,s);
}
void fnInputArray(int N,int *s)
{
int i;
for(i=1;i<=N;i++){
scanf("%d",&*(s+i));
}
}
void fnDisplayArray(int N,int *s)
{
int i;
for(i=1;i<=N;i++){
printf("%d\t",*(s+i));
}
}
void fnBubbleSort(int N,int *s)
{
int i,j,temp;
for(i=1;i<=(N-1);i++){
for(j=1;j<=(N-i);j++){
if(*(s+j)>*(s+j+1)){
temp=*(s+j);
*(s+j)=*(s+j+1);
*(s+j+1)=temp;
}
}
}
}


OUTPUT 1
Program to sort elements in an array using bubble sort
Enter the size of an array
5
Enter the 5 elements in an array
66
33
58
98
63
The elements in an array are:
66 33 58 98 63
The elements in an after sorting are:
33 58 63 66 98 [141740@localhost ~]$

OUTPUT 2
Program to sort elements in an array using bubble sort
Enter the size of an array
4
Enter the 4 elements in an array
33
55
11
2
The elements in an array are:
33 55 11 2
The elements in an after sorting are:
2 11 33 55 [141740@localhost ~]$

No comments:

Post a Comment