The basic concept of a bubbling sort (bubblesort) is to compare the adjacent two numbers in turn, place decimals in front, and large numbers behind. That is, first compare the 1th and 2nd numbers, put the decimals before the large number. Then compare the 2nd and 3rd numbers, place the decimal before the large number, and then continue until you compare the last two numbers, put the decimals before the decimal, and put the large number behind. Repeat the above process, still starting from the first logarithm comparison (because it may be due to the 2nd and 3rd number of exchanges, so that the 1th number is no longer greater than the 2nd number), the decimal place before, after the large number of places, has been compared to the minimum number of pairs of neighbors, the decimal place before the large number, the second end, Get a new decimal in the penultimate number. So go on until the final sort is finished.
Since the decimal is always placed forward in the sorting process, the large number is placed backwards, which is the equivalent of bubbles rising, so called bubble sort.
In the programming implementation, it is generally implemented with a double loop, the outer loop variable is set to I, the inner loop variable is set to J. The outer loop repeats n times, and the inner loop repeats in turn n-1, N-2, ..., 1 times. Each comparison of the two elements are related to the inner loop j, they can be identified by a[j] and a [j+1], the value of I is 1, 2, ...., n, for each of the i,j values are 1, 2, ..., n-i, for example, the following code:
1for (int i = 0, i < arrys.length; i++) { 2for (int j = 0;j < arrys.length-i-1; J + +) { 3 if//Determine the current number with the size of the back number 4 //Put the large number behind 5 } 6 } 7 }
The following is the code implementation for this topic:
1 PackageCom.fhcq.bubblesort;2 3 Public classBubblesort {4 5 //Main method6 Public Static voidMain (string[] args) {7 int[] arr = {3, 5, 7, 1, 8, 11, 9};//define Arrays8Bubblesort (arr);//Start sort9}Ten One //Sorting methods A Public Static voidBubblesort (int[] Arrys) { - //define temporary variable temp - inttemp = 0; the //Use J as subscript to iterate through the array - for(intj = 0; J < Arrys.length; J + +) { - //For each array element, from 0 to the future sort of the largest subscript, always put the largest number in the back - for(intK = 0;k < arrys.length-j-1; k++) { + if(Arrys[k] > Arrys[k+1]) {//Determine the size of the current and subsequent numbers -temp = Arrys[k]; +ARRYS[K] = arrys[k+1]; AARRYS[K+1] = temp;//change value with TEMP variable at} -} -} -Bubbleprint (Arrys);//Print -} - //Printing method in Public Static voidBubbleprint (int[] before) { - for(inti = 0;i < before.length; i++) {//Traversal toSystem.out.print (Before[i] + " ");//print, separated by spaces +} -System.out.println ();//Line break the} *}
Implementing a bubbling sorting algorithm with Java