Bubbling sorting is the most basic and simplest of all sorting algorithms. The idea is to exchange the sort, by comparing and exchanging adjacent data to achieve the purpose of sorting. The process is as follows: 1. Compare the size of the adjacent two data to the data in the array to be sorted. 2, if the previous data is greater than the data behind, the two data exchange. After such a round of comparison and exchange, the smallest data is placed at the top of the array, 3, according to the above comparison and Exchange method, the rest of the data for the same operation, and finally, you can follow the order from small to large sequence to complete the sorting. If there is initial data: 25 11 45 26 12 78. 1, the first round of sorting, starting from the head of the array to compare. The first is 25 and 11 comparisons, 25 large, and data 11 moving forward one bit. Similarly, compare 25 and 45, the latter one is 45 large, the position does not move. Then compare 45 and 26, the previous number is large, so 45 is shifted one bit later. After the first round of sorting, the order is: [11, 25, 26, 12, 45, 78]. 2, the second round of sorting, starting from the head of the array to compare. The first is 11 and 25 comparison, because the front number is small, so the position does not move. Comparing 25 and 26, the position does not move because the number of the front is small. After the second round of sorting, the order is: [11, 25, 12, 26, 45, 78]. 3, the third round of sorting, starting from the head of the array to compare. The first is 11 and 25 comparison, because the front number is small, so the position does not move. Compare 25 and 12, because of the large number of fronts, so the position is interchangeable. After the third round of sorting, the order is: [11, 12, 25, 26, 45, 78]. ...... 4. After the final round of sorting, the order is: [One, A, a, a, a.] Java code is implemented as:
1 Public int[] Sort (int[] arr) {2 inttmp;3 for(inti = 1; i < arr.length; i++) {4 //determine the size of the adjacent two data and bubble the larger number back5 for(intj = 0; J < Arr.length-1; J + +) {6 if(Arr[j] > arr[j+1]) {7TMP =Arr[j];8ARR[J] = arr[j+1];9ARR[J+1] =tmp;Ten } One } ASYSTEM.OUT.PRINTLN (i + ":" +arrays.tostring (arr)); - } - returnarr; the}
The bubble sort of Java implementation of common algorithm