Algorithm description: For a given n records, the two adjacent records are compared in sequence from the first record. When the current record is greater than the subsequent record, the exchange position is performed. After one round of comparison and exchange, the largest record among the n records will be at the nth position; then the second round of comparison is performed on the previous (n-1) records; the process is repeated until there is only one record left for the comparison.
Bubble sorting is very easy to understand. Taking sorting from small to large as an example, each round of sorting finds the maximum value in the unsorted sequence and puts it at the end.
Suppose the length of the array is N:
(1) Compare the two adjacent data in front and back. If the previous data is greater than the next data, exchange the two data.
(2) After traversing the 0th data of the array to N-1 data once, the largest data will be "sinked" to the N-1th position of the array.
(3) N=N-1. If N is not 0, repeat the previous two steps, otherwise the sorting will be completed.
The above is the basic idea of bubble sorting, and you can write code quickly according to this definition.
package sorting;/** * Bubble sort* Average O(n^2), best O(n), worst O(n^2); Space complexity O(1); Stable; Simple* @author zeng * */public class BubbleSort {public static void bubbleSort(int[] a){int n = a.length;int temp = 0;for (int i=0;i<n;i++){for (int j=0;j<ni-1;j++){if(a[j]<a[j+1]){temp = a[j];a[j] = a[j+1];a[j+1] = temp;}}}} public static void main(String[] args){int[] a ={49,38,65,97,76,13,27,50};bubbleSort(a); for (int j:a) System.out.print(j+" ");}}Summarize
The above is all about the simple implementation of Java bubble sorting, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!