The bubbling algorithm, as its name implies, is the data arranged in a certain order.
Algorithm ideas:
Suppose there is an array of such
Int[] arr = {5, 9, 3, 1, 2, 6, 7, 4, 8};
According to the algorithm definition, the output we need is
Int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
First, get our original array. Determine the size of arr[0] and arr[1] first. If ARR[0]>ARR[1], their location is exchanged. Then compare the sizes of arr[1] and arr[2], and if arr[1]>arr[2], swap their positions. And so on, after iterating through an array, you can put the largest number at the end of the array. At this point this step was performed by Arr. Length-1 times, both 8 times. Then the second round is executed, and the second largest number is moved to the second-to-last position of the array by traversing the comparison array size. You can then arrange the given array in a new order by bubbling the sort.
About the computation of time complexity:
The first round performed m times, the second round carried out m-1 times, which carried out altogether m-rounds.
So the corresponding time complexity is: O ((1+m)/2) *m. When the smaller constants are ignored, the time complexity of the bubble sort is O (m^2)
Enclose the code implemented by C #:
Static int[] arr = {5, 9, 3, 1, 2, 6, 7, 4, 8}; static void Main (string[] args) {for (int i = 0; i < arr. Length-2; i++) {for (int j = 0; J < arr. Length-1-I; J + +) { if (Arr[j] < Arr[j + 1]) { bubbling (J, j + 1); }}} foreach (Var A in arr) { Console.WriteLine (a); } Console.read (); } static void bubbling (int one, int) { int buff = Arr[one]; Arr[one] = Arr[two]; Arr[two] = buff; }
Small Fat sheep Algorithm learning-----bubble sort