Skip to content

Instantly share code, notes, and snippets.

@ivankahl
Created June 3, 2015 17:48
Show Gist options
  • Save ivankahl/c654f3c28df936831ac6 to your computer and use it in GitHub Desktop.
Save ivankahl/c654f3c28df936831ac6 to your computer and use it in GitHub Desktop.
Visual C#: Bubble Sorting Algorithm
private static int[] BubbleSort(int[] numbers)
{
// Create a boolean to store whether the list has been sorted or not
bool sorted = false;
do
{
// Set our sorted value to true. This will be set to false if
// any values have to be swapped
sorted = true;
// Loop through each item in the array. We got to Length - 1
// as we check numbers[i] against numbers[i + 1] and therefore
// don't want to get an OutOfRange error
for (int i = 0; i < numbers.Length - 1; i++)
{
// Check if the next item (i + 1) is greater than the
// current item (i)
if (numbers[i] > numbers[i + 1])
{
// If so, swap the values
int tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = tmp;
// Change our boolean to false
sorted = false;
}
}
} while (!sorted);
return numbers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment