Bubble sort idea: Compare the two adjacent elements to match the required exchange position.
In the example, the adjacent two elements are compared, the large put to the right, the final realization from small to large sort.
The first step: first implement the maximum value in an array at the far right:
Public Static voidMain (String args[]) {int[] arr = {12,4,2,34,8};//defines an array of arrBubblesort (arr);//Call Method BubblesortSystem.out.println ("After sorting:");//Print the final result for(inti = 0;i<arr.length;i++) {System.out.print (Arr[i]+","); } } Public Static voidBubblesort (int[] arr) { for(inti = 0; i<arr.length-1;i++){ if(arr[i]>arr[i+1]){ inttemp =Arr[i]; Arr[i]= Arr[i+1]; Arr[i+1] =temp; } } }
Print it as follows:
After sorting is:
4,2,12,8,34,
Step two: Send the second largest value to the left of the last one.
Add the following code snippet:
for (int i = 0;i<arr.length-1-1;i++) { if(arr[i]>arr[i+1]) { int temp = arr[i]; = Arr[i+1]; Arr[i+1] = temp; } }
Similarly, one analogy, and finally the number from small to large sorting;
Summarize our code,
Public Static voidMain (String args[]) {int[] arr = {8,34,4,2,12}; Bubblesort (arr); Definition method Bubblesort System.out.println ("After sorting:"); for(inti = 0;i<arr.length;i++) {System.out.print (Arr[i]+","); } } Public Static voidBubblesort (int[] arr) { for(intj = 0;j<arr.length-1;j++{//j is used to control the number of wheels, as long as the length-1 wheel for(inti = 0;i<arr.length-1-j;i++) {I is used to control the comparison and switching between two numbersif(arr[i]>arr[i+1]){ inttemp =Arr[i]; Arr[i]= Arr[i+1]; Arr[i+1] =temp; } } } }
After sorting is:
2,4,8,12,34,
Implementation of Java bubbling sorting