Using bubble sort arrange numbers in ascending order. Simple  C program Sorting is the arrangement of data in the required manner. In...

Bubble sort : C program simple

Using bubble sort arrange numbers in ascending order.

Simple C program

Sorting is the arrangement of data in the required manner. In this blog we will be discussing about one such type that is Bubble sort and here we have given a simple c program for the explanation.
Such type of questions can be ask in rtmnu Nagpur university cse 3rd sem question papers.
Also in last of the blog we have given link to download rtmnu cse 3rd sem question papers.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:

5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Using bubble sort arrange numbers in ascending order.
Bubble sort
AnmolViidya

#include<stdio.h>
int main(){
int a[]={12,23,34,45,34,35,56,970,73};
//bubble sort
int temp,i,j,n=(sizeof(a)/sizeof(int));
for(i=0;i<n-1;i++)
{
    for(j=0;j<n-1-i;j++)
    {
        if(a[j]>a[j+1])
        {
            temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
    }
}
for(i=0;i<n;i++)
    printf("%d\t",a[i]);
    printf("\ngreatest is %d",a[10]);
    printf("\nsmallest is %d",a[0]);
return 0;
}


0 comments: