[JavaSE] array (sort-bubble sort), javase bubble
Two-layer nested loop, the number of outer control loops, and comparison of inner Loops
for(int x=0;x<arr.length-1;x++){ for(int y=0;y<arr.length;y++){ if(arr[y]>arr[y+1]){ } } }
At this time, the Code has a problem. The inner loop compares the sorted parts, all at the end, and needs to be removed.
for(int x=0;x<arr.length-1;x++){ for(int y=0;y<arr.length-x;y++){ if(arr[y]>arr[y+1]){ } } }
At this time, the Code has a problem. The last element of the inner loop cannot be compared with the one after it.
for(int x=0;x<arr.length-1;x++){ for(int y=0;y<arr.length-x-1;y++){ if(arr[y]>arr[y+1]){ } } }
After judgment, the two variables are switched to the location, using third-party Variables
for(int x=0;x<arr.length-1;x++){ for(int y=0;y<arr.length-x-1;y++){ if(arr[y]>arr[y+1]){ int temp=arr[y]; arr[y]=arr[y+1]; arr[y+1]=temp; } } }
Java version:
Public class ArrayDemo {/*** @ param args */public static void main (String [] args) {int [] arr = new int [] {2, 5, 4, 1 }; int [] newArr = bubbleSort (arr); for (int x: newArr) {System. out. print (x) ;}/ *** bubble sort (positive) * @ param arr * @ return */public static int [] bubbleSort (int [] arr) {for (int x = 0; x <arr. length-1; x ++) {for (int y = 0; y <arr. length-x-1; y ++) {if (arr [y]> arr [y + 1]) {int temp = arr [y]; arr [y] = arr [y + 1]; arr [y + 1] = temp ;}} return arr ;}}
PHP version:
<? Phpclass ArrayDemo {public static function main () {$ arr = array (2, 5, 4, 1); print_r (ArrayDemo: bubbleSort ($ arr )); // output Array ([0] => 1 [1] => 2 [2] => 4 [3] => 5)}/*** bubble sort (positive) * @ param arr * @ return */public static function bubbleSort ($ arr) {for ($ x = 0; $ x <count ($ arr)-1; $ x ++) {for ($ y = 0; $ y <count ($ arr)-$ X-1; $ y ++) {if ($ arr [$ y]> $ arr [$ y + 1]) {$ temp = $ arr [$ y]; $ arr [$ y] = $ arr [$ y + 1]; $ arr [$ y + 1] = $ temp ;}}return $ arr ;}} ArrayDemo :: main ();
The performance of sorting and Bubble Sorting is very low, which improves the performance. When you need to change the position, do not change first. First place the angle to be changed to the stack memory, wait for the last one-time swap in the heap memory
The fastest sorting is the hill sorting.