Today I will show you a simple example bubble sort algorithm.
First, create a new C# console project with the name BubbleSort001.
About the bubble sort algorithm, you can read more on the Wikipedia webpage.
Let’s see the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using System; namespace BubbleSort001 { class Program { // create a class for the bubble sort algorithm static void BubbleSort001(int[] array) { Console.WriteLine("Bubble sort example algorithm!"); // start a point for sorting int count = 0; // for each element in the array then use two loops for (int i = array.Length -1; i > 0; i--) { for (int j = 0; j < i; j++) // condition for sorting if(array[j] > array[j + 1]) { // use a temp buffer to translate values int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; // counting each steep count++; } } } // testing the class BubbleSort001 static void Main(string[] args) { // define array for sorting int[] array = {3,2,1,5,4}; // print the array foreach (int nr in array) Console.Write(" " + nr); Console.WriteLine(); // use the class and sort the array BubbleSort001(array); // print the result foreach(int nr in array) Console.Write(" " + nr); } } } |
The result of the running source code is this:
1 2 3 4 | BubbleSort001>dotnet run 3 2 1 5 4 Bubble sort example algorithm! 1 2 3 4 5 |