Bubble Sort is a sorting algorithm (an algorithm that puts elements of a list in a certain order). The simplest sorting algorithm is Bubble Sort. In the Bubble Sort, as elements are sorted they gradually “bubble up” to their proper location in the array, like bubbles rising in a glass of soda.
Example:
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 | static void Main(string[] args) { int[] number = { 20, 50, 15, 42, 19, 93, 50 }; bool flag = true; int temp; int numLength = number.Length; //sorting an array for (int i = 1; (i <= (numLength - 1)) && flag; i++) { flag = false; for (int j = 0; j < (numLength - 1); j++) { if (number[j + 1] > number[j]) { temp = number[j]; number[j] = number[j + 1]; number[j + 1] = temp; flag = true; } } } //Sorted array foreach (int num in number) { Console.Write("\t {0}", num); } Console.Read(); } |
Output: