**Sorting** is a technique for organizing the elements in an **increasing** or **decreasing** order. Bubble Sort is a comparison-based algorithm in which the adjacent elements are compared and swapped to maintain the order.

**Bubble Sort Algorithm**

Bubble sorting is the simplest sorting algorithm that works by comparing two adjacent elements in an array and swapping them if found in the wrong order.

Bubble sort compares the first element with the next one and if found in the wrong order then that compared element in an array are swapped. This algorithm traverse through the entire element in an array.

**C# Program for Bubble Sort**

There is an unsorted list of arrays given in a program. With the help of bubble sort, we sort those array lists in ascending order.

**Source code:** The following is the C# program to implement bubble sort.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System; class BubbleSort { static void Main(string[] args) { int[] array = { 56, 67, 2, 675, 11, 45, 8, 765, 18 }; int temp; Console.WriteLine("Bubble Sort in C#"); Console.Write("Unsorted Array are: "); for (int i = 0; i < array.Length; i++) Console.Write(array[i] + " "); for (int j = 0; j <= array.Length - 2; j++) { for (int i = 0; i <= array.Length - 2; i++) { if (array[i] > array[i + 1]) { temp = array[i + 1]; array[i + 1] = array[i]; array[i] = temp; } } } Console.Write("\nAfter Bubble Sorting:"); foreach(int p in array) Console.Write(p + " "); Console.Read(); } } |

The Output of Bubble Sort program in C#

**Time Complexity of Bubble Sort:**

- Best case: O(n)
- Average case: O(n^2)
- Worst case: O(n^2)