It is best to understand Bubble Sorting in sorting. Each time we compare an element with all other elements, we know that this element is placed in a reasonable position, this operation is executed repeatedly on the next adjacent element, knowing that all elements are executed, and the final result is the sorted array.
Public class BubbleSort {public void bubbleSort (int [] pArray) {if (pArray = null) {throw new NullPointerException ();} // The array contains n elements, loop n times for (int I = 0; I <pArray. length-1; I ++) {// compare the current element in the array with other n-1 elements for (int j = 0; j <pArray. length-i-1; j ++) {if (pArray [j]> pArray [j + 1]) {swap (pArray, j, j + 1 );}}}} /*** swap two values in the array */private void swap (int [] pArray, int pX, int pY) {int temp = pArray [pX]; pArray [pX] = pArray [pY]; pArray [pY] = temp ;}}
Main method used for testing
public static void main(String[] args) {int[] arr = {3, 5, 1, 10, 0, 100, 3, 9};BubbleSort bubbleSort = new BubbleSort();bubbleSort.bubbleSort(arr);for (int i = 0; i < arr.length; i++) {System.out.println("value = "+ arr[i]);}}
* Another method: {3, 5, 1, 10, 0,100, 3, 9 }, the sorting rule increases sequentially from left to right (that is, the left value is smaller than the right value)
Public void bubbleSortTwo (int [] pArray) {if (pArray = null) {throw new NullPointerException () ;}for (int I = 0; I <pArray. length; I ++) {// The left side of I is sorted for (int j = I + 1; j <pArray. length; j ++) {if (pArray [I]> pArray [j]) {swap (pArray, I, j );}}}}
* The sorting rule is descending from right to left (that is, the values on the right are greater than those on the left)
Public void bubbleSortThree (int [] pArray) {if (pArray = null) {throw new NullPointerException () ;}for (int I = pArray. length-1; I> = 0; I --) {// The right side of I is sorted for (int j = pArray. length-1; j> = I; j --) {if (pArray [I]> pArray [j]) {swap (pArray, I, j );}}}}
Time Complexity: 1 + 2 + 3 +... + (n-1) = n * (n-1)/2 = O (N square)
Best case: O (n) only needs to be compared and judged once.
Worst case: O (n square)
Space complexity: O (1) because no auxiliary space is used