You are on page 1of 5

C program for bubble sort

C program for bubble sort: c programming code for bubble sort to sort numbers or arrange them
in ascending order. You can easily modify it to print numbers in descending order.

Bubble sort algorithm in c


/* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c <
{
for (d = 0 ; d
{
if (array[d]
{
swap
array[d]
array[d+1]
}
}
}

( n - 1 ); c++)
< n - c - 1; d++)
> array[d+1]) /* For decreasing order use < */
= array[d];
= array[d+1];
= swap;

printf("Sorted list in ascending order:\n");


for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}

Download Bubble sort program.

Output of program:

Bubble sort in c language using function


#include <stdio.h>
void bubble_sort(long [], long);
int main()
{
long array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);
for (c = 0; c < n; c++)
scanf("%ld", &array[c]);
bubble_sort(array, n);
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%ld\n", array[c]);
}

return 0;

void bubble_sort(long list[], long n)


{
long c, d, t;
for (c = 0 ; c < ( n - 1 ); c++)
{

for (d = 0 ; d < n - c - 1; d++)


{
if (list[d] > list[d+1])
{
/* Swapping */

}
}

t
= list[d];
list[d]
= list[d+1];
list[d+1] = t;

Program To Sort Elements using Bubble Sort


Algorithm
/*C Program To Sort data in ascending order using bubble sort.*/
#include <stdio.h>
int main()
{
int data[100],i,n,step,temp;
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("%d. Enter element: ",i+1);
scanf("%d",&data[i]);
}
for(step=0;step<n-1;++step)
for(i=0;i<n-step-1;++i)
{
if(data[i]>data[i+1]) /* To sort in descending order, change > to < in this
line. */
{
temp=data[i];
data[i]=data[i+1];
data[i+1]=temp;
}
}
printf("In ascending order: ");
for(i=0;i<n;++i)
printf("%d ",data[i]);

return 0;
}

Enter the number of elements to be sorted: 6


1. Enter element: 12
2. Enter element: 3
3. Enter element: 0
4. Enter element: -3
5. Enter element: 1
6. Enter element: -9
In ascending order: -9 -3 0 1 3 13

c program for bubble sort

#include<stdio.h>
#include<conio.h>
int main( )
{
int a[100];
int i, j, temp, n ;
printf("how many numbers you want to sort : \n");
scanf("%d",&n);
printf("Enter %d number values you want to sort\n", n);
for(j=0; j<n; j++)
scanf("%d",&a[j]);

for(j=1;j<n;j++)
{
for(i=0; i<n; i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
getch();
}

output of c program for bubble sort:

c program for bubble sort

You might also like