Showing posts with label Implementation of Bubble Sort. Show all posts
Showing posts with label Implementation of Bubble Sort. Show all posts

Sunday, February 15, 2015

Implementation of Bubble Sort

AIM:
          To write a C program to implement bubble sort

ALGORITHM:
            Step 1: Start the program.
Step 2: Bubble sort algorithm starts by comparing the first two elements of an
            array and swapping if necessary,
Step 3: if you want to sort the elements of array in ascending order and if the first
            element is greater than second then, you need to swap the elements but, if
            the first element is smaller than second, you mustn't swap the element.
Step 4: Then, again second and third elements are compared and swapped if it is
necessary and this process go on until last and second last element is compared and swapped. This completes the first step of bubble sort.
Step 5: If there are n elements to be sorted then, the process mentioned above
            should be repeated n-1 times to get required result.
Step 6: Exit

PROGRAM 
#include<stdio.h>
int main()
{
int s,temp,i,j,a[20];
printf("Enter total numbers of elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
//Bubble sorting ALGORITHM
for(i=s-2;i>=0;i--)
{
for(j=0;j<=i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

printf("After sorting: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
return 0;
}