# Bubble Sort Algorithm in C#

# Bubble Sort Algorithm in C#

### One of the first sorting algorithms in computer science students learn is the Bubble Sort. We take a look at what it is using C# and how it performs.

Join the DZone community and get the full member experience.

Join For FreeAccess NoSQL and Big Data through SQL using standard drivers (ODBC, JDBC, ADO.NET). Free Download

In this article, I am going to explain the Bubble Sort algorithm. Bubble Sort is one of the most widely used sorting algorithms for programmers worldwide. It can be applied to any collection including arrays, strings, numbers, or characters.

Bubble Sort is very frequently asked about in job interviews. So first, I am going to explain the Bubble Sort algorithm. Then, I will be providing C# code to execute it.

**The Bubble Sort Algorithm**

This algorithm follows the concept of iterating through the array from the first index to the last index and comparing adjacent elements and then swapping them if they appear in the wrong order; i.e. if the next element is smaller than the current element, they are swapped.

Let's understand this with the help of an example. Let us take an input array as **8 5 7 3 1**.

The sorted output for this array is **1 3 5 7 8**.

Let's see the step-by-step execution of the Bubble Sort algorithm on the input array to get the sorted output.

```
Iteration 1: – 8 5 7 3 1 → 5 8 7 3 1 → 5 7 8 3 1 → 5 7 3 8 1→ 5 7 3 1 8
Iteration 2: – 5 7 3 1 8 → 5 3 7 1 8→ 5 3 1 7 8
Iteration 3: – 5 3 1 7 8 → 3 5 1 7 8 → 3 1 5 7 8
Iteration 4: – 3 1 5 7 8 → 1 3 5 7 8
Iteration 5: – 1 3 5 7 8
```

Hence, we got the sorted array in iteration 5.

## Time Complexity

Since we need to iterate the entire array for every element, the average and the worst case complexity of Bubble Sort is O(n²).

**Conclusion**

In this tutorial, we learned about the Bubble Sort algorithm and its implementation using C#.

You can download the source code from here.

You can find my other articles on algorithms here.

The fastest databases need the fastest drivers - learn how you can leverage CData Drivers for high performance NoSQL & Big Data Access.

Published at DZone with permission of Ankit Sharma , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

## {{ parent.title || parent.header.title}}

## {{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}