Bubblesort in C

by david 24. June 2010 18:45

Just for fun Surprised 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);

    }

  }

}

Tags: ,

Code

About the author

David

I'm a C# developer having worked with .Net since it was in beta.  Before that I mainly worked in C and C++.  I have been developing commercial software for more than 20 years.  I also mess around with microprocesors, but that's just for fun.  I live near Cambridge, England and at the moment I'm contracted to one of the departments at Cambridge University.

Related Links

Tag cloud