Sorting Algorithms — Bubble Sort
Bubble sort is one of the stable searching algorithms which has a simple implementation.
It is so slow for many inputs and it might be used in practice. Bubble sort swaps two elements of an array at a time until the array is sorted.
It has a time complexity of O(n ²) and a space complexity of O(1).
Let’s check an example
We have an array that consists of 9 unsorted numbers and we should sort it ascending.
int[] array = { 2, 6, 7, 9, 5, 0, 1, 4, 3 };
We need a boolean value to check if there is a swap process or not
bool swapProcess = true;
We need a while loop to proceed with the bubble sort process until the array is sorted
while(swapProcess)
We set the boolean value to false because we need to make sure there is a swap process in for loop.
swapProcess = false;
Now, we need a for loop to touch each element of the input of the array
for(int i=0;i<array.Length-1;i++)
i has to be less than array.Length-1 otherwise you will get an error Index was outside the bounds of the array. That is because bubble sort is checking two elements of the array at a time.
The last process is to swap the elements.
if (array[i] > array[i+1])
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapProcess = true;
}
Here is all code
int[] array = { 2, 6, 7, 9, 5, 0, 1, 4, 3 };
SortBubble(array);
void SortBubble(int[] array)
{
bool swapProcess = true;
while(swapProcess)
{
swapProcess = false;
for(int i=0;i<array.Length-1;i++) // asc sort
{
if (array[i] > array[i+1])
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapProcess = true;
}
}
}
foreach (var item in array)
{
Console.Write(item);
}
}
If you create a console application and execute the result, you will see the result like one the below