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
#include <stdio.h>
#include<conio.h>
void main()
{
int array[100], n, i, j, swap;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i=0; i < n; i++)
scanf("%d", &array[i]);
for (i= 0 ; i < ( n - 1 ); i++)
{
for (j = 0 ; j < n - i - 1; j++)
{
if (array[j] > array[j+1])
{
swap = array[j];
array[j] = array[j+1];
array[j+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( i= 0 ; i < n ; i++ )
printf("%d\n", array[i]);
getch();
}
Output of program:
Bubble sort in c language using function
#include <stdio.h>
#include<conio.h>
void bubble_sort(long [], long);
void main()
{
long array[100], n, i;
clrscr();
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);
for (i = 0; i < n; i++)
scanf("%ld", &array[i]);
bubble_sort(array, n);
printf("Sorted list in ascending order:\n");
for ( i = 0 ; i < n ; i++ )
printf("%ld\n", array[i]);
getch();
}
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;
}
}
}
}
No comments:
Post a Comment