The bubbling sorting algorithm works as follows: (from small to large)
- Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
- Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
- Repeat the above steps for all elements, except for the last one.
- Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
Python:
A = [3,99,2,11,66]n = Len (a) for I in Range (n-1): #进行n-1 trip for J in Range (n-i-1): if A[J] > a[j+1]: a[j],a[j +1] = A[j+1],a[j] print ("%d order results:"% (i+1), a) print ("Final sort result:", a)
1th Order Results: [3, 99, 2, 11, 66]
1th Order Results: [3, 2, 99, 11, 66]
1th Order Results: [3, 2, 11, 99, 66]
1th Order Results: [3, 2, 11, 66, 99]
2nd order Results: [2, 3, 11, 66, 99]
2nd order Results: [2, 3, 11, 66, 99]
2nd order Results: [2, 3, 11, 66, 99]
3rd order Results: [2, 3, 11, 66, 99]
3rd order Results: [2, 3, 11, 66, 99]
4th order Results: [2, 3, 11, 66, 99]
Final sort Result: [2, 3, 11, 66, 99]
Java:
public class Test{public static void Main (string[] args) { int i, J; Int[] a= {3,99,2,11,66}; int n = a.length; For (i=0, i<n-1; i++) {for (j=0; j<n-i-1; J + +) { if (A[j] > a[j+1]) { int temp = a[j];< C10/>A[J] = a[j+1]; a[j+1]=temp; } System.out.print ("No." + (i + 1) + "sequencing results:"); for (int k=0;k<n;k++) { System.out.print (a[k]+ "\ t"); } System.out.print ("\ n");} } System.out.print ("Final sorting Result:"); for (i=0;i<n;i++) { System.out.print (a[i]+ "\ t");} }}
Practice bubbling sorting using Python and Java, respectively