Bubble Sort is one of the simpler sorting algorithms in programming. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. Repeat the work of visiting the array until there are no more elements that need to be exchanged, which means that the array has been sorted.
Bubble sort is like bubbles emerging from water, in bubble sort the smallest or largest number, depending on whether we are sorting the array in ascending or descending order, the bubbles pop up towards the beginning or end of the array.
1) Compare adjacent elements. If the first one is larger than the second one, swap them two.
2) Do the same for every pair of adjacent elements, starting with the first pair and ending with the last pair, at which point the last element should be the largest number.
3) Repeat the above steps for all elements except the last one.
4) Keep repeating the above steps for fewer and fewer elements until there are no pairs of numbers to compare.
Bubble sort performs poorly compared to other sorting algorithms such as quick sort, merge sort, or shell sort. The average case complexity of these algorithms is O(nlogn), while the average case complexity of bubble sort is O(n^2).
In the best case, bubble sort is better than quicksort with O(n) performance. Bubble sort is three times slower than quick sort or merge sort, even with n=100, but it is easier to implement and remember.
The complexity and performance of bubble sort are as follows:
1) Worst case performance of bubble sort is O(n^2)
2) The best case performance of bubble sort is O(n)
3) The average performance of bubble sort is O(n^2)
//Bubble sort publicstaticvoidbubbleSort(int[]arr){//The outer loop is used to control the number of turns of the array loop for(inti=0;i<arr.length-1;i++){//The inner loop is used to Complete the comparison of element values and swap the larger element values to the back for(intj=0;j<arr.length-1-i;j++){if(arr[j]>arr[j+1]){inttemp= arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}//Output result for(intn:nums){System.out.println(n);} }
For example:
publicclassMain{publicstaticvoidmain(String[]args){inta[]={6,1,15,32,9};for(inti=1;i<a.length;i++){for(intj=0;j<a .length-1;j++){if(a[j]>a[j+1]){inttemp=a[j];a[j]=a[j+1];a[j+1]=temp ;}}}System.out.println(The result of bubble sorting is:);for(inttemp:a){System.out.print(temp+);}}}
The running results are as follows:
The result of bubble sort is: 1691532
You can try it out yourself!