Bubble Sort) is a simple sorting algorithm. It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.
The Bubble Sorting Algorithm operates as follows:
Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements until no one pair of numbers needs to be compared.
Code implementation:
Public class BubbleSort {public static void sort (long arr []) {// defines the Temporary Variable long temp = 0; for (int I = 0; I <arr. length-1; I ++) {// This loop indicates the number of records in the loop // The second loop indicates the comparison between the two numbers connected for (int j = arr. length-1; j> I; j --) {// exchange data if (arr [j] <arr [J-1]) {temp = arr [j]; arr [j] = arr [J-1]; arr [J-1] = temp ;}}} test: public class TestSort {public static void main (String [] args) {// initialize the array and add the long arr [] = new long [5]; arr [0] = 34; arr [1] = 3; arr [2] = 4; arr [3] = 23; arr [4] = 33; // data System before sorting is not performed. out. print ("["); for (long num: arr) {System. out. print (num + "");} System. out. print ("]"); System. out. println (); // The sorted data BubbleSort. sort (arr); System. out. print ("["); for (long num: arr) {System. out. print (num + "");} System. out. print ("]") ;}}
This article from the "A rain and dust" blog, please be sure to keep this source http://13145200724.blog.51cto.com/6263780/1300710