1. Basic Ideas
(1) Compares two adjacent elements in the array. If the first one is larger than the second, then the interchange.
(2) for each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair, for example: the first tree and the second tree comparison, the first number is greater than the second is exchanged, then the second and the third comparison, the second large exchange ... Finally, the maximum number is moved to the last.
(3) Repeat the above steps to complete n-1 times
2. Time-Complicated
(1) Best case: The sequence is in ascending order, in this case, the comparison operation that needs to be performed is (n-1) times. The swap operation is 0 times. i.e. O (n)
(2) Worst case scenario: the sequence is in descending order, then there are N (n-1)/2 times to be performed at this time. The interchange operand is the same as the comparison operand. i.e. O (n^2)
(3) Progressive time complexity (average time complexity): O (n^2)
3. Code implementation
1 namespaceBubblesortprogram2 {3 Public class Program4 {5 Static voidMain (string[] args)6 {7 Encoding.registerprovider (codepagesencodingprovider.instance);8 int[] Arry = {9,7, A,6,8,1};9Console.WriteLine ("-------------before sorting--------------");Ten for(inti =0; I < Arry. Length; i++) One { AConsole.Write (arry[i]+" "); - } - Bubblesort (arry); theConsole.WriteLine ("\ n-------------after sorting--------------"); - for(inti =0; I < Arry. Length; i++) - { -Console.Write (arry[i]+" "); + } - Console.readkey (); + } A at /// <summary> - ///Bubble Sort - /// </summary> - /// <param name= "Arry" ></param> - Public Static voidBubblesort (int[] arry) - { in if(Arry. Length = =0|| Arry = =NULL) - return; to for(inti =0; I < Arry. Length-1; i++) + { - for(intj =0; J < Arry. Length-i-1; J + +) the { * if(Arry[j] > arry[j +1]) $ {Panax Notoginseng vartemp = arry[j+1]; -Arry[j +1] =Arry[j]; theARRY[J] =temp; + } A } the } + } - } $}
Operation Result:
Bubble sort of sorting algorithm