Saturday 2 August 2014

Bubble Sort - Recurrsion


Provided below is the Bubble Sorting C-Code based on a recursive algorithm instead of a iteration algorithm. It is the most basic and novice sorting algorithm.
The time complexity is O(n2).

The worst case time complexity is O(n2).
The average case time complexity is also O(n2).
The Bubble sort algo provided below has two functions other than main function namely, bubble sort - for sorting of the array and display - for the printing of the sorted array.

The code provided below uses recursive algorithm for the sorting purpose instead of itterative algorithm. 

//Bubblesort with recurrsion

#include<stdio.h>

#define MAX 10

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,i;

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

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

        {

            temp=*(p+i+1);

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

            *(p+i)=temp;

        }

        bubblesort(p,q-1);

    }

}



void display(int *p,int *q)

{

    for(;p<q;p++)

    printf("%d ",*p);

}


No comments:

Post a Comment