Description: Welcome to criticize and correct, leave a message and like!
This article will illustrate the principle of bubble sort through a simple example, gossip less and go directly to the code.
1 /** 2 * Bubble sort 3 * 4, 6, 2, 3, 5 4 * Idea: write the inner loop first (traversal times: times = arr.length - 1), arrange the first number, and then add Outer loop, sort all numbers 5 * iterate over the first result: 6 * _____________ 7 * 4, 6, 2, 3, 5 8 * 4, 2, 6, 3, 5 9 * 4, 2, 3, 6, 5 10 * 4, 2, 3, 5, 6 11 */ 12 public class BubbleSortDemo { 13 public static void main(String[] args) { 14 int [] arr = {4, 6, 2, 3, 5 }; 15 bubbleSort(arr); 16 for( int i = 0; i < arr.length; i++ ) { 17 System.out.println(arr[i]); // 2, 3, 4, 5, 6 18 } 19 } 20 /** 21 * Bubble Sort 22 */ 23 public static void bubbleSort( int [] arr) { 24 int len = arr.length; 25 int temp = 0 ; 26 /* 27 Outer loop: control the number of the sorted number 28 Inner loop : Control the number of comparisons between two adjacent numbers 29 The relationship between the two (i < len - 1 and j < len - 1 - i): As the outer loop arranges one more number, the inner loop will be compared once less. 30 */ 31 for (int i = 0; i < len - 1; i++) { 32 for (int j = 0; j < len - 1 - i; j++) { 33 if (arr[j] > arr[j+1]) { 34 temp = arr[j]; 35 arr[j] = arr[j+1]; 36 arr[j+1] = temp; 37 } 38 } 39 } 40 } 41 42 }