Bubble Sort Program is the Simplest Sorting in C
Introduction
Bubble Sort is the simplest sorting algorithm that can be done by repeatedly swapping the adjacent elements if they are in wrong order. It is named as bubble sort since it looks like bubbles the lighter elements come up and heavier elements settle down.
Algorithm
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
(A) if a[i] < a[j]
Then interchange a[i] and a[j]
[End of if]
(B) Set j = j+1
[End of Inner Loop]
[End of Step 1 Outer Loop]
Step 4: Exit
Complexity O(n2)
C Program
//C program Bubble Sort Program
#include <stdio.h>
#include <conio.h>
int main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("\nArray after sorting: ");
for(i=0;i<n;++i)
printf("%d ",a[i]);
getch();
return 0;
}
Output
0 Comments
Blog
Active User (0)
No Active User!