Write a c program to sort a 1d array using pointer by applying bubble sort technique.
Answers
#include<stdio.h>
int *a[100],x,y,it;
void main()
{
void sort(),display();
int x;
clrscr();
printf("\n Enter the number of elements in the array\n");
scanf("%d",&it); //taking elements from user
printf("\n Enter %d numbers\n",it);
for(x=0;x<it;++x)
scanf("%d",&a[x]);
sort(); //sort function to perform bubble sort
display(); //display function to display elements
}
void sort() //sort function to sort elements
{
int swap=1,*temp;
for(x=0;x<it && swap==1;++x)
{
swap=0;
for(y=0;y<it-(x+1);++y)
if (a[y]>a[y+1])
{
temp=a[y];
a[y]=a[y+1];
a[y+1]=temp;
swap=1;
}
}
}
void display()
{
printf("\n Sorted elements are as follows :\n");
for(x=0;x<it;++x)
printf("%d\n",a[x]);
getch();
}
Answer:
Program to sort an array using bubble sort technique is as follows:-
Explanation:
#include<stdio.h>
void main()
{
int arr [ 5 ] = { 11, 33, 10, 8, 2 };
// loop which will sort the array
for ( int i = 0 ; i < 5 ; i ++ )
{
for ( int j = i+1 ; j < 5 ; j++)
{
if ( arr [ i ] < arr [ j ] )
{
int swap = arr [ i ];
arr [ i ] = arr [ j ];
arr [ j ] = swap;
}
}
// Now the next loop will display the sorted array
for ( int i = 0 ; i < 5 ; i ++ )
{
printf ( " %d ", arr [ i ] );
}
}//end of program