C# Bubble sorting
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sort { class BubbleSorter { public static int[] Sort(int[] a) { BubbleSort(a); return a; } private static void BubbleSort(int[] myArray) { for (int i = 0; i < myArray.Length; i++)//循环的趟数 { for (int j = 0; j < myArray.Length - 1- i; j++)//每次循环的次数 { //比较相邻元素,将值大的后移==》每一趟循环结束==》最后一个数是最大的。 //所以每次循环都比上一次循环的个数少1,即j < myArray.Length - 1- i if (myArray[j] > myArray[j + 1]) { Swap(ref myArray[j], ref myArray[j + 1]); } } } } //引用参数与值参数 private static void Swap(ref int left, ref int right) { int temp; temp = left; left = right; right = temp; } } } 冒泡排序算法的运作如下:
The bubble sorting algorithm operates as follows:
1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number. ==》The last number does not need to be compared, because it is the largest.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.
The above is the content of C# bubble sorting. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!