Skip to content

Instantly share code, notes, and snippets.

@mattslay
Last active September 14, 2019 00:11
Show Gist options
  • Save mattslay/84895f6ff97b49275f8845812cfbe930 to your computer and use it in GitHub Desktop.
Save mattslay/84895f6ff97b49275f8845812cfbe930 to your computer and use it in GitHub Desktop.
Bubble Sort example in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
var list = new int[10] { 7, 2, 9, 4, 70, 1, 8, 5, 2, 6 };
bool modified = false;
int loopCount = 0;
while (modified || loopCount == 0)
{
modified = false;
for (int z = 0; z < list.Length -1; z++)
{
int current = list[z];
int next = list[z+1];
if (next < current)
{
// Swap the elements
list[z] = next;
list[z + 1] = current;
modified = true;
}
}
loopCount++;
Console.WriteLine(loopCount);
}
Console.WriteLine("Done...");
// Display the sorted array
for(int x = 0; x < list.Length; x++)
{
Console.WriteLine(list[x]);
}
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment