C# Bubble Sort class
This is a simple demonstration of a Bubble Sort class. It takes the form of an overloaded function Sort that requires the array to be sorted and a parameter and an optional parameter to indicate if the sort is to be increasing or decreasing. The function returns the sorted array.
I have also included the Visual Studio project folder including a simple program showing how it works. It creates an array and fills it with a set of random digits and then sorts it.
public class BubbleSort
{
// Overloaded function to allow sorting with an implied direction
public int[] sort(params int[] sorting)
{
return sort(true, sorting);
}
/* Sorting routine, requires at boolean value for ascending or decending
* and an array of int for the actual values to be sorted */
public int[] sort(Boolean ascending, params int[] sorting)
{
Boolean swapped = false;
int counter = sorting.Length;
int temp;
do
{
swapped = false;
for (int i = 0; i < counter - 1; i++)
{
/* check to see which direction we are sorting in. There are
* more efficient (in terms of code length) ways of doing this
* but this is easier to read */
if (ascending)
{
if (sorting[i] > sorting[i + 1])
{
temp = sorting[i];
sorting[i] = sorting[i + 1];
sorting[i + 1] = temp;
swapped = true;
}
}
else
{
if (sorting[i] < sorting[i + 1])
{
temp = sorting[i];
sorting[i] = sorting[i + 1];
sorting[i + 1] = temp;
swapped = true;
}
}
}
counter--;
} while (swapped);
return sorting;
}
}
Bubble Sort example