Bubble Sorting in C#

Basically theres many ways to sort a data structure like Arrays. One of the simplest sorting algorithms to learn is called the bubble sort. Personally its one of the first ones I learned.

In plain terms, a bubble sort works by going through the array and comparing until the smallest value or item in the array “floats” to the top while the bigger values “sink” to the bottom.

For instance, suppose we have an array of integers that contain: 64,32,512,128,16,3

What the bubble sort does is, goes through the array once, makes a comparison between two integers, and switches the order of the values in the array, then when  until all the values make the comparison statement true, thats when the sorting stops.

So to illustrate a bit more:

First pass:
[32,64,128,512,3,16] we see that 32 and 64 have been switched, 128 and 512 have been switch, and 3 and 16 have been switched, but we’re not done yet because we still need to put 3 and 16 into their respective order

Second pass:
[32,64,128,3,16,512], again, going through and swapping values, we’re not done yet since 3 and 16 are not in order

Third pass:

Fourth pass:

Fifth pass:

The bubble sort has O(n^2) in its worst and average case complexity in performance, in its best case its O(n).  Its best suited for sorting small collections of data rather than big collections.

Code in C#, you can also use this for Java as well since the syntax is very similar:

int[] arr = {5,3,7,6,1};

int temp = 0; //a temporary int, to store a value when switching positions
//from smallest to largest
for(int outer =  0; outer < arr.Length; outer++)//this nested for loop is the main tool to do the sorting
      for(int inner = 0; inner < arr.Length - 1; inner++)
            if(arr[inner] > arr[inner + 1])//comparison statement
                  temp = arr[inner + 1];
                  arr[inner + 1] = arr[inner];
                  arr[inner] = temp;//switching done

//write the numbers onto the command prompt
for(int i = 0; i < arr.Length; i++)

Animation of algorithm


One thought on “Bubble Sorting in C#

  1. Pingback: Quicksort | Bits and Pieces of Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s