Bubble sort (Bubble sort) is a simple sort algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.
The bubbling sorting algorithm works as follows:
Compares the adjacent elements. If the first one is bigger than the second one, swap them both. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
Repeat the above steps for all elements, except for the last one. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
PackageBubblesort;ImportJava.util.Arrays; Public class Demo01 { //First version Static voidBubblesort (int[] arr) {intlen = arr.length; for(intj=0; j<len-1; j + +) { for(intI=0; i<len-1; i++) {if(arr[i]>arr[i+1]){inttemp = Arr[i]; Arr[i] = arr[i+1]; arr[i+1] = temp; }} System.out.println (Arrays.tostring (arr)); } }//second Edition each trip reduces the number of times per trip Static voidBubblesortsecond (int[] arr) {intlen = arr.length; for(intj=0; j<len-1; j + +) { for(intI=0; i<len-1-j;i++) {if(arr[i]>arr[i+1]) {inttemp = Arr[i]; Arr[i] = arr[i+1]; arr[i+1] = temp; }} System.out.println (Arrays.tostring (arr)); } }//Third version /** * Final version: Assuming that the data is in order, the latter is ordered after a certain trip, reducing the number of trips * E.G. 81234 * First trip 12348 * Second Trip 12348 * @param args * / Static voidBubblesortthird (int[] arr) {Booleansorted =true;intlen = arr.length; for(intj=0; j<len-1; j + +) {sorted =true;//assumed order for(intI=0; i<len-1-j;i++) {if(arr[i]>arr[i+1]) {inttemp = Arr[i]; Arr[i] = arr[i+1]; arr[i+1] = temp; sorted =false;//Assuming failure}} System.out.println (Arrays.tostring (arr));if(sorted) { Break; } } } Public Static void Main(string[] args) {System.out.println ("===========1============");int[] arr = {9,2,7,3,4}; Bubblesort (arr); System.out.println ("===========2============"); arr =New int[] {9,1,7,3,4}; Bubblesortsecond (arr); System.out.println ("===========3============"); arr =New int[] {9,1,7,3,4}; Bubblesortthird (arr); }}
Operation Result:
===========1============[2, 7, 3, 4, 9][2, 3, 4, 7, 9][2, 3, 4, 7, 9][2, 3, 4, 7, 9]===========2============[1, 7, 3, 4, 9][1, 3, 4, 7, 9][1, 3, 4, 7, 9][1, 3, 4, 7, 9]===========3============[1, 7, 3, 4, 9][1, 3, 4, 7, 9][1, 3, 4, 7, 9]
Bubble sort (Java edition)