by david
24. June 2010 18:45
Just for fun
I decided to write a bubblesort algorithm in C. The idea is that I have a collection of rank structures and the ones with the lowest values in the errors variable will come to the top.
Now I have decided to keep it for posterity. Of course, in reality I've used qsort() instead; so the code below is for recreational purposes ... or something.
typedef struct rank
{
double errors;
int element;
};
void swap(struct rank *array, int a, int b)
{
struct rank temp = array[a];
array[a] = array[b];
array[b] = temp;
}
int swapIfBigger(struct rank *array, int a, int b)
{
if (array[b].errors>=array[a].errors) return 0;
swap(array,a,b);
return 1;
}
void bubblesort(struct rank *array, int len)
{
int t=0,count=1;
while (count>0)
{
count=0;
for (t=0; t<len-1; t++)
{
count += swapIfBigger(array,t, t+1);
}
}
}