Friday, November 22, 2013

Bubblesort algorithm implementation in C

Here is a bubblesort implementation in C. Although bubblesort is not a efficient algorithm, its a simple algorithm to demonstrate what is a sorting algorithm


Asymptotic Complexity
Time ComplexitySpace Complexity
n^21


If you want to see the same implementation in python please click the following link: Bubblesort implementation in python

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
void bubblesort(int *arr, int size)
{
int i = 0, temp;
int j = 1;
bool swapped = true;
while(swapped)
{
swapped = false;
i = 0;
for(i; i< size-j; i++)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
swapped = true;
}
}
j++;
}
}
main()
{
int arr[] = { 12,4,6,7,33,43,87,32,7,34,2,8,43,23,7,3};
int i;
int size = sizeof(arr)/sizeof(arr[0]);
for (i=0; i<size; i++)
printf(" %d",arr[i]);
bubblesort(arr, size);
printf("\n");
for (i=0; i<size; i++)
printf(" %d",arr[i]);
}
view raw bubblesort.c hosted with ❤ by GitHub