Monday 20 February 2017

Bubble Sort

Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

#include<stdio.h>

void main()
{
    int ar[5],i,j,tmp,flag=0;   
    for(i=0;i<5;i++)
    {
        printf("Enter number>> ");
        scanf("%d",&ar[i]);
    }
    printf("\n\nUnsort Array\n");
    for(i=0;i<5;i++)
        printf("%d\t",ar[i]);
    for(i=0;i<5-1;i++)
    {
        flag=0;
        for(j=1;j<5-i-1;j++)
        {
            if(ar[j]>ar[j+1])
            {
                tmp=ar[j];
                ar[j]=ar[j+1];
                ar[j+1]=tmp;
                flag=1;
            }
        }
        if(flag==0);
            break;
    }
    printf("\n\n");
    for(i=0;i<5;i++)
        printf("%d\t",ar[i]);   
}

No comments:

Post a Comment