The bubbling sort is each traversal. The adjacent numbers are compared, the former is larger than the latter, and the maximum value is shifted back to the last position; The key point of the algorithm is to determine the boundary of each cycle;
The following two algorithms are a certain degree of improvement to bubble sort, but the bubble sort performance is still poor compared with other sorting algorithms.
Bubble sort public class Bubble_sort {//The original solution public void Bubble_sort1 (int[] data) {int n = data.length;for (int i = 0; i < n; i++) {//Note the index range of the loop to avoid overflow for (int j = 0; J < n-i-1, j + +) {if (Data[j] > data[j + 1]) {Swap (data, J, j + 1);}}} Improved algorithm, by introducing a flag to determine whether a loop has a movement, if no move, then//the order has been completed, do not need to continue the next cycle public void Bubble_sort2 (int[] data) {int n = Data.length;boolean flag = true;//Indicates whether moving int index = n-1; Mark the last one that needs to be cycled//once in motion, continue looping while (flag) {flag = false;for (int j = 0; J < Index-1; J + +) {if (data[j] > Dat A[j + 1]) {Swap (data, J, j + 1); flag = True;}} index--;}} Improved algorithm two: When a traversal, the last m-bit is not converted, it means that the next n-bit is larger than the current maximum number//According to the bubble sort, each sink into the maximum, then these bits must have been ordered public void Bubble_sort3 (int[] data) { int n = Data.length;int index = n-1;while (Index! = 0) {int k = 0;for (int j = 0; J < Index-1; J + +) {if (Data[j] > Da Ta[j + 1]) {Swap (data, J, j + 1); k = j;}} index = k;}} Cannot use reference implementations like C + +, so it has to be changed with the data array private void Swap (int[] data, int a, int b) {int temp = Data[a];d ata[a] = data[b];d ata[b] = temP;} public void Print_array (int[] data) {for (int num:data) {System.out.print (num); System.out.print ("");}} public static void Main (string[] args) {Bubble_sort bubble_sort = new Bubble_sort (); int data[] = {2,34,45,2,13,24,5,24,57} ; bubble_sort.bubble_sort3 (data); Bubble_sort.print_array (data);}}
Sort algorithm bubble sort (Java)