Bubble sort is an algorithm of sorting an array whereby larger elements will be push to the back of the array.
The bubble sort (ascending to descending) code in C#:
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 | using System; class Program { static void Main(string[] args) { int [] array = new int [10] {100, 50, 20, 40, 10, 60, 80, 70, 90, 30}; int array_size = 10; Console.WriteLine("The array before Bubble Sort is: "); for (int i = 0; i < array_size; i++){ Console.WriteLine("array[" +i +"] = " +array[i]); } // Now we will use bubble sort int temp; for (int index = array_size - 2; index >= 0; index--) { for (int i = 0; i <= index; i++) { if (array[i] > array[i + 1]) { temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; } } } Console.WriteLine(); Console.WriteLine("The array after Bubble Sort is: "); for (int i = 0; i < array_size; i++) { Console.WriteLine("array[" + i + "] = " + array[i]); } } } |
Here is a dancing video illustrating bubble sort:










