Algorithm

Bubble Sort Algorithm In C#

Introduction

In this article, I am going to explain the Bubble sort algorithm. Bubble sort is one of the most widely used sorting algorithms by the programmers worldwide. It can be applied to any collection including array, string, 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 a 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 us understand this with the help of an example. Let us take an input array such as – 8 5 7 3 1

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

Let us see the step by step execution of the Bubble sort algorithm on the input array to get the sorted output.

  1. 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
  2. Iteration 2: – 5 7 3 1 8 → 5 3 7 1 8→ 5 3 1 7 8
  3. Iteration 3: – 5 3 1 7 8 → 3 5 1 7 8 → 3 1 5 7 8
  4. Iteration 4: – 3 1 5 7 8 → 1 3 5 7 8
  5. 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²).

See Also

Conclusion

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

You can download the source code from here

Ankit Sharma

Full Stack Consultant | GDE for Angular | Microsoft MVP | Author | Speaker | Passionate Programmer

Recent Posts

Announcing A New Blazor Course

Introduction Blazor is a .NET web framework that allows us to create client-side applications using…

3 years ago

How To Solve Sudoku Using Azure Form Recognizer

Introduction In this article, we are going to create a sudoku solver with the help…

3 years ago

Going Serverless With Blazor

Introduction In this article, we will learn how to implement Azure serverless with Blazor web…

4 years ago

Announcing A Free eBook On Angular and Firebase

Introduction Angular is an open-source framework that allows us to create applications for multiple platforms…

4 years ago

Optical Character Reader Using Angular And Azure Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Angular…

4 years ago

Optical Character Reader Using Blazor And Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Blazor…

4 years ago