Bubble Sort is a sorting algorithm (an algorithm that puts elements of a list in a certain order). The simplest sorting algorithm is Bubble Sort. In the Bubble Sort, as elements are sorted they gradually "bubble up" to their proper location in the array, like bubbles rising in a glass of soda.
The Bubble Sort works by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary. This process is repeated as many times as necessary, until the array is sorted.

When this first pass through the array is complete, the Bubble Sort returns to elements one and two and starts the process all over again. The Bubble Sort has stopped when it is finished examining the entire array and no "swaps" are needed.
To sort an array there will be n-1 passes where n is the number of elements in the array. In the above diagram there are seven elements in an array so there will be 7-1=6 passes.

Bubble Sort Algorithm
Procedure BubbleSort(DATA : list of sortable items)
N= DATA.Length
- Set Flag := True
- Repeat Steps from 3 to 5 for I = 1 to N-1 while Flag == true
- Set Flag := False
- Set J:=0. [Initialize pass pointer J]
- Repeat while J<N-1 [Executes pass]
(a) If DATA[J+1]>DATA[J], then:
Swap DATA[J] and DATA[J+1]
Set Flag:= True
[End of If structure]
(b) Set J:=J+1
[End of inner loop]
[End of step 1 outer loop] - Exit
Bubble Sort in C#
using System;
namespace SortingExample
{
class Program
{
static void Main(string[] args)
{
int[] number = { 89, 76, 45, 92, 67, 12, 99 };
bool flag = true;
int temp;
int numLength = number.Length;
//sorting an array
for (int i = 1; (i <= (numLength - 1)) && flag; i++)
{
flag = false;
for (int j = 0; j < (numLength - 1); j++)
{
if (number[j + 1] > number[j])
{
temp = number[j];
number[j] = number[j + 1];
number[j + 1] = temp;
flag = true;
}
}
}
//Sorted array
foreach (int num in number)
{
Console.Write("\t {0}",num);
}
Console.Read();
}
}
}
Output


Shahroz KhanPosted Mar 28, 2020, 11:00 AM
No need of flag.
Željko PerićPosted Oct 6, 2018, 1:48 AM
What about multidimensional bubble sort algorithm ?
johnson yuanPosted Jul 29, 2014, 12:12 PM
Hi, I think its better in the nested for statement: for(int j = 0; j < length - i -1; ++j), you don't have to iterate all the array in the nested for.
Feroz MdPosted Nov 25, 2013, 3:17 AM
how to do this for 2d array but rather then swapping count the no of inversion