Sunday 21 February 2016

Bubble sort program in C

Bubble Sort

Simple bubble sort program in C. It simply works on the concept of bubbles. However, we can improve the normal bubble sort program by keeping track of whether or not the given array is already sorted, if it is already sorted then we can break the loop (Already sorted would mean that no swap would occur). 
The complexity of the bubble sort algorithm is O(N2). Bubble sort program in C is as shown below.

#include<stdio.h>
int main(){
    int i,j,t,swap,a[1000000],flag;
    printf("Enter the number of elements: ");
    scanf("%d",&t);
    for(i=0;i<t;i++)
        scanf("%d",&a[i]);
    for(i=0;i<t-1;i++)
        for(j=0;j<t-i-1;j++)
              if(a[j]>a[j+1]){
                    swap=a[j];
                    a[j]=a[j+1];
                    a[j+1]=swap;
              }
    for(i=0;i<t;i++)
        printf("%d\n",a[i]);
    return 0;
}


C code for Improved bubble sort

#include<stdio.h>
int main(){
    int i,j,t,swap,a[10000],flag;
    printf("Enter the number of elements: ");
    scanf("%d",&t);
    for(i=0;i<t;i++)
        scanf("%d",&a[i]);
    for(i=0;i<t-1;i++){
        flag=0;
        for(j=0;j<t-i-1;j++){
              if(a[j]>a[j+1]){
                    swap=a[j];
                    a[j]=a[j+1];
                    a[j+1]=swap;
                    flag=1;
              }
        }
        if(flag){
             break;       
        }
    }
    for(i=0;i<t;i++)
        printf("%d\n",a[i]);
    return 0;
}

Also see: Merge Sort , Insertion sort

No comments:

Post a Comment