[Basic idea]
Bubble sort is a sort of exchange, and its basic idea is to compare the keywords of the adjacent records by 22, if the reverse order is exchanged until there are no reversed records.
[Java Implementation]
public class Bubblesort {public static void main (string[] args) {int[] arr = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1, 8}; System.out.println ("Before sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");} Bubblesort (arr); System.out.println (); System.out.println ("After sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");}} /** * Bubble sort */private static void Bubblesort (int[] arr) {for (int i = 0; i < arr.length; i++) {for (int j = 0; J < ar R.length-1-I; J + +) {if (Arr[j] > arr[j + 1]) {//Compare adjacent elements Swap (arr, j);//data exchange}}}}/** * data exchange */private static void Swap (int[] arr, int j) {int tmp = ARR[J];//data exchange arr[j] = arr[j + 1];arr[j + 1] = tmp;}}
[algorithm optimization]
Suppose the column to be sorted is: {2, 1, 3, 4, 5, 6, 7, 8, 9} After swapping 2 and 1, the sequence is ordered, but the algorithm still loops through it many times, although there is no data to be exchanged.
When the sub-cycle of the entire cycle of the side, there is no data to exchange, indicating that the sequence has been ordered, there is no need to cycle judgment.
We can add a marker field to improve the algorithm.
public class BubbleSort2 {public static void main (string[] args) {int[] arr = {2, 1, 3, 4, 5, 6, 7, 8, 9}; System.out.println ("Before sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");} Bubblesort (arr); System.out.println (); System.out.println ("After sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");}} /** * Bubble sort */private static void Bubblesort (int[] arr) {Boolean flag = true;for (int i = 0; i < arr.length && F Lag i++) {flag = false;for (int j = 0; J < arr.length-1-I; j + +) {if (Arr[j] > arr[j + 1]) {swap (arr, j); flag = true; }}}}/** * data exchange */private static void Swap (int[] arr, int j) {int tmp = Arr[j];arr[j] = arr[j + 1];arr[j + 1] = tmp;}}
Java Sorting algorithm (i): bubble sort