In bubble sort algorithm, we pick the two elements of the collection one by one from the start and compare them. If first element is larger than the second element then we swap them, and then continue the procedure till the end of the collection. Like see we have a string array like below
string[] str = {"e","c","b","d","a" };
so, first we will pick first two elements and will compare them
if(e>c)
{
// we will swap both the elements.
// so our array will be like this now
str = {"c","e","b","d","a" };
}
In next step we will pick the elements e , b and will compare them same rule will apply on it. If firs one will be greater then the second one then we will swap them then the array will be look like this:
str = {"c","b","e","d","a" };
we will continue the process until we got the whole array in the sorted form.
check the below function to sort a string array with bubble sort algorithm:
string[] str = {"e","c","b","d","a" };
so, first we will pick first two elements and will compare them
if(e>c)
{
// we will swap both the elements.
// so our array will be like this now
str = {"c","e","b","d","a" };
}
In next step we will pick the elements e , b and will compare them same rule will apply on it. If firs one will be greater then the second one then we will swap them then the array will be look like this:
str = {"c","b","e","d","a" };
we will continue the process until we got the whole array in the sorted form.
check the below function to sort a string array with bubble sort algorithm:
private static void BubbleSort2(string[] list)
{
var keepMoving = true;
while (keepMoving)
{
keepMoving = false;
for (var i = 0; i < list.Length - 1; i++)
{
var x = list[i];
var y = list[i + 1];
if (string.Compare(x, y) > 0)
{
list[i] = y;
list[i + 1] = x;
keepMoving = true;
}
}
}
for (var j = 0; j < list.Length; j++)
{
Console.WriteLine(list[j]);
}
}