Suppose, you have an unsorted array of 5 elements
Here first iteration compare the first value with the second value
Now continue the iteration 4 times ie, n-1 times where n is the number of elements in an array
After 4 iterations the array will be as follows,
It's very easy to implement the above algorithm not only using C# but also in every programing languages. Here's an example program
//Method for bubble sorting
public void bubble(List<int> sort)
{
//set a temporary variable
int tempvar;
//Iterate through n-1 times
for (int i = 1; i <= sort.Count; i++)
{
//loop through each elements in all iterations
for (int j = 0; j < sort.Count-i; j++)
{
//compare each value with the following value,
//if greater then swap, else continue to next consecutive pair
if (sort[j] > sort[j + 1])
{
tempvar = sort[j];
sort[j] = sort[j + 1];
sort[j + 1] = tempvar;
}
}
}
//display sort
display(sort);
}
//Input array: {3,2,4,1,5}
Output:
1,2,3,4,5