Saturday 2 August 2014

Bubble Sort


Bubble Sort

The Code provided below is the C-code for bubble sorting technique of an array.
Bubble sort is considered as the most simplest of the sorting algorithms with a time complexity of O(n2) and is mostly used for sorting the arrays of limited elements.

The efficiency of the algorithm is compared in terms of number of comparisons.
In bubble sort algorithm there is (n-1) comparisons in first loop, (n-2) comparisons in second loop and so on.
So, there is total of (n-1) + (n-2) + ..... + 2 + 1 comparisons. Thus, the total no. of comparisons are
n*(n-1)/2. Thus, leading to the time complexity of O(n2).


//Bubblesort without recursion

#include<stdio.h>

#define MAX 5

void bubblesort(int *,int *);

void display(int *,int *);

int main()

{

    int a[MAX],n,i;

    printf("Enter the no. of elements in the array,where MAX=%d: ",MAX);

    scanf("%d",&n);

    for(;n>MAX;scanf("%d",&n))

    printf("The value entered is greater than MAX.Please re-enter the value: ");

    printf("Enter the elements of the array: \n");

    for(i=0;i<n;i++)

    scanf("%d",&a[i]);

    printf("The unsorted array: ");

    display(a,a+n);

    printf("\n");

    bubblesort(a,a+n);

    printf("The sorted array: ");

    display(a,a+n);

    return 0;

}



void bubblesort(int *p,int *q)

{

    if(p!=q)

    {

        int temp,j,i;

        for(i=0;p<q-i-1;i++)

        for(j=0;p<q-j-i-1;j++)

        if(*(p+j)>*(p+j+1))

        {

            temp=*(p+j+1);

            *(p+1+j)=*(p+j);

            *(p+j)=temp;

        }

    }

}



void display(int *p,int *q)

{

    for(;p<q;p++)

    printf("%d ",*p);

}

No comments:

Post a Comment