Directory (?) [+] Introduction to bubble sort algorithm
The bubble sort is simpler than the insertion sort, pushing the largest element progressively to the highest bit (currently dealing with the highest bit of the child array). As I understand it, bubble sequencing is a layer-by-layer process . The top is built, and the sort is good. The worst time to run the bubble sort is O (N2), which is the same as the insertion order. Bubble Sort algorithm Java implementation
Like the Java implementation of insert sort (insertsort), implement an Array tool class first. The code is as follows:[Java] View Plain copy public class arrayutils { public static void printarray (Int[] array) { system.out.print ("{"); for (int i = 0; i < array.length; i++) { system.out.print (Array[i]); if (i < array.length - 1) { system.out.print (", "); } } system.out.println ("}"); } public static void exchangeelements (INT[]&NBSP;ARRAY,&NBSP;INT&NBSP;INDEX1,&NBSP;INT&NBSP;INDEX2) { int temp = array[index1]; array[index1] = array[index2]; array[index2 ] = temp; } }
Gradually select N-1 to 1 (Java inside the array to start with the 0 tag), respectively, as the top of the n,n-1,...,2 layer, the 2nd layer after the top, only a smaller element, the sorting end. Each top of the building Chengdu starting from position 0, in turn, and the next position of the elements, if more than the next one, exchange between the two positions. The Java implementation of the bubble sort and the test code are as follows:[Java] View plain copy public class bubblesort { public static void main (String[] args) { int[] array = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3 }; system.out.println ("Before sort: "); Arrayutils.printarray (array); bubblesort (array); system.out.println ("After sort:"); &nbSp; arrayutils.printarray (array); } public static void Bubblesort (Int[] array) { if (array.length <= 1) { return; } int size = array.length; for (int i = size - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (array[j] > array[j + 1]) { Arrayutils.exchangeelements (array, j, j + 1); } } } } }