Bubble sort is a simple sorting algorithm. It 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
/************************************************************/
/* File name : Bubble.c */
/* Description : Performs bubble sort */
/* Author : admin of copensource.blogspot.com */
/* Date & version : Oct 27th 2009 */
/* Copy Right : C open source holds all rights to this code. Codes */ can be re-used by any individual for non commerical purpose only */
/*Tested : VC 2005, 0-errors, 0-warnings */
/************************************************************/
#define DEBUG 1
#define INP_SAMPLE 10
/* Input, assuming 10 samples of 32-bit */
int inp[INP_SAMPLE] = {12, 4, 36, 29, 10, 11, 3, 5, 17, -1};
/* Output, same as of input array size */
int out[INP_SAMPLE];
#include "stdio.h"
void main()
{
int tmp, a;
int i, j, k, swap;
for(i = INP_SAMPLE; i > 0; i--)
{
/* For first time 'a' contains inp[0], which is taken as refernce */
a = inp[INP_SAMPLE - i];
/* Index for swapping */
swap = INP_SAMPLE - i;
/* Comparing 'a' with rest of inp elements */
for(j = (INP_SAMPLE - i); j < INP_SAMPLE; j++)
{
/* Swapping */
if(a > inp[j])
{
tmp = inp[j];
inp[j] = a;
inp[swap] = tmp;
a = tmp;
}
}
#if DEBUG
for(k = 0; k < INP_SAMPLE; k++)
printf("%d\t",inp[k]);
#endif
}
}
/* End of bubble sort */
0 comments:
Post a Comment