Bubble Sort:
is to compare the next two elements by index, if greater than/less than (depending on the need to ascending or descending order), then displace, otherwise do not change
Such a round down, compared n-1 times, n equals the number of elements; n-2, n-3 ... Until the last round, compared 1 times
So the number of comparisons is decremented: from n-1 to 1
Then the total number of comparisons is: 1+2+3+...+ (n-1), calculated in a linear formula: (1+n-1)/2* (n-1) ==> n/2* (n-1) ==> (n^2-n) * 0.5
Use large o to indicate the time complexity of the algorithm: O (n^2), ignoring the coefficients 0.5 and constant-n
public class Bubblesort {public static void main (string[] args) {int len = 10;int[] ary = new Int[len]; Random random = new random (), for (int j = 0; J < Len; J + +) {Ary[j] = random.nextint (1000);} SYSTEM.OUT.PRINTLN (------before-------Sort); for (int j = 0; J < Ary.length; J + +) {System.out.print (Ary[j] + "");} /* * Ascending, ASC1 and ASC2 optimize the comparison of internal loops, better * total comparisons: * Asc1, ASC2: (1+n-1)/2* (n-1) ==> n/2* (n-1) ==> N (n-1)/2 ==> (n^2-n)/2 * Asc:n^2-n *///orderasc (ary);//orderasc2 (ary); orderAsc1 (ary);//Descending, just the size of the replacement}static void Orderasc (int[] ary) { int count = 0;//number of comparisons int len = ary.length;for (int j = 0; J < Len; J + +) {//outer fixed loop count for (int k = 0; k < len-1; k++) {//inner fixed loop count if (Ary[k] > ary[k + 1]) {Ary[k] = ary[k + 1] + (ary[k + 1] = ary[k]) * 0;//One-step interchange/* Swap two variable values * a=a+b * b=a-b * A=a-b */} count++;}} System.out.println ("\ n-----orderasc in ascending order------number of times:" + count); for (int j = 0; J < Len; J + +) {System.out.print (Ary[j] + " ");}} static void OrderAsc1 (int[] ary) {int count = 0;//number of comparisons int lEn = ary.length;for (int j = 0; J < Len; J + +) {//outer fixed loop count for (int k = len-1; k > J; k--) {//inner layer from multiple to less decrement comparison if (Ary[k] < Ary[k-1]) {ary[k] = Ary[k-1] + (ary[k-1] = ary[k]) * 0;//one-step Exchange} count++;} System.out.println ("\ n-----orderAsc1 in ascending order------number of times:" + count); for (int j = 0; J < Len; J + +) {System.out.print (Ary[j] + " ");}} static void OrderAsc2 (int[] ary) {int count = 0;//number of comparisons int len = ary.length;for (int j = len-1; j > 0; j--) {//outer layer fixed cycle times Number */* k < J; Total comparison times = (n^2-n)/2 */for (int k = 0; k < J; k++) {//inner layer from multiple to less decrement comparison if (Ary[k] > ary[k + 1]) {Ary[k] = ary[k + 1] + (ary[k + 1] = ary[k]) * 0;//One-step Exchange}count++;}} System.out.println ("\ n-----orderAsc2 in ascending order------number of times:" + count); for (int j = 0; J < Len; J + +) {System.out.print (Ary[j] + " ");}}}Print
Java Implementation Bubble Sort