Bubble sort algorithm in C

Bubble sort is a basic sorting algorithm where the elements rise to the top of the list. The picture below illustrates the algorithm.

Bubble sort in action

Performance

Quadratic on average and linear in best case. The algorithm does not perform well when the number of elements is high.

This example demonstrates bubble sort by sorting an array of integer elements.

#include <stdio.h>

void Bubblesort(int* elements, int length);

int main(){

  // Define an unsorted array of integer elements
  int unsorted[] = {9,5,17,6,8,2,4,39,18,3};
  int i;

  for(i=0;i<10;i++){
    printf("%d ",unsorted[i]);
  }

  // Sort the elements
  Bubblesort(unsorted,10);

  printf("\n");

  for(i=0;i<10;i++){
    printf("%d ",unsorted[i]);
  }

  return 0;
}

void Bubblesort(int* elements, int length){
  int i;

  if(length > 0){
    for(i=0;i<length;i++){
      int first = elements[i];
      int second = elements[i+1]; 

      if(second < first){
        // Swap
        int tmp = elements[i+1];
        elements[i+1] = elements[i];
        elements[i] = tmp;
      }
    }

    // Recursive call
    Bubblesort(elements,length-1);
  }
}

Output:

$ touch bubblesort.c
$ vi bubblesort.c
$ gcc bubblesort.c -o bubblesort
$ ./bubblesort
9 5 17 6 8 2 4 39 18 3
0 2 3 4 5 6 8 9 17 18
$ gcc -v
Using built-in specs.
[snip]
gcc version 4.3.2 …

 

This entry was posted in C and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Paul Marufu
    Posted February 15, 2013 at 10:53 am | Permalink

    this is not working. the program is not running and is saying Type mismatch in redeclaration of “Bubblesort”

    • Posted February 16, 2013 at 11:28 am | Permalink

      Hi Paul,

      Works on my machine:

      $ touch bubblesort.c
      $ vi bubblesort.c
      $ gcc bubblesort.c -o bubblesort
      $ ./bubblesort
      9 5 17 6 8 2 4 39 18 3
      0 2 3 4 5 6 8 9 17 18
      $ gcc -v
      Using built-in specs.
      [snip]
      gcc version 4.3.2 …

      Best regards,

      Ferhat

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?