Description: Welcome to criticize correct, message praise! If reproduced, please specify the original address: http://www.cnblogs.com/chris0710/p/8995234.html
This article will explain the bubble sort principle by simple example, gossip less, direct on the code.
1 /**2 * Bubble Sort3 * 4, 6, 2, 3, 54 * Idea: Write the inner Loop first (number of times = arr.length-1), arrange the first number, and then add the outer loop to arrange all the numbers .5 * Traverse the first result:6 * _____________7 * 4, 6, 2, 3, 58 * 4, 2, 6, 3, 59 * 4, 2, 3, 6, 5Ten * 4, 2, 3, 5, 6 One */ A Public classBubblesortdemo { - Public Static voidMain (string[] args) { - int[] arr = {4, 6, 2, 3, 5}; the Bubblesort (arr); - for(inti = 0; i < arr.length; i++) { - System.out.println (Arr[i]);//2, 3, 4, 5, 6 - } + } - /** + * Bubble Sort A */ at Public Static voidBubblesort (int[] arr) { - intLen =arr.length; - inttemp = 0; - /* - Outer loop: Control the number of rows. - Inner Loop: Control the number of adjacent two number of comparisons in the relationship between the two (I < len-1 and J < len-1-i): As the outer loop is more than 1 numbers, the inner loop is less cyclic compared. - */ to for(inti = 0; i < len-1; i++) { + for(intj = 0; J < len-1-I; J + +) { - if(Arr[j] > arr[j+1]) { thetemp =Arr[j]; *ARR[J] = arr[j+1]; $ARR[J+1] =temp;Panax Notoginseng } - } the } + } A the}
finally: recommend a super practical visualization tool, the purpose is to be able to interactively see the program each step of the state and parameters is what, simply perfect!
Visualization tool Address: Http://www.pythontutor.com/java.html#mode=edit
The interface is as follows:
Java Bubble sort