Learn about bubble sorting

Key points

Bubble sorting is an exchange sort.

What is exchange sorting?

Exchange sorting: Compare the keywords to be sorted in pairs, and exchange the logarithm that does not satisfy the order requirements until the entire table satisfies the order requirements.

Algorithmic thinking

It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if they are in the wrong order. The work of visiting the series is repeated until no more exchanges are needed, which means that the sequence has been sorted.

The name of this algorithm comes from the fact that the smaller the element will slowly "float" to the top of the series via the exchange, hence the name.

Suppose there is an unordered sequence of size N. Bubble sorting is to find the i-th small (large) element through the pairwise comparison in each sorting process, and move it up.

Learn about bubble sorting

The above picture is an example to demonstrate the actual flow of bubble sorting:

Suppose there is an unordered sequence { 4. 3. 1. 2, 5 }

The first order: by comparing the two, find the first small value of 1, and put it in the first place of the sequence.

Second ordering: By comparing the two pairs, find the second smallest value of 2 and place it in the second position of the sequence.

The third order: by comparing the two pairs, find the third smallest value of 3 and place it in the third place of the sequence.

At this point, all the elements are already in order and the sorting is over.

To turn the above process into code, we need to think like a machine, otherwise the compiler can't read it.

Suppose you want to sort an unordered sequence of size N in ascending order (ie, from small to large).

(1) The i-th small element needs to be found by comparison during each sorting process.

So, we need an outer loop that starts at the beginning of the array (subscript 0) and scans until the second last element (ie subscript N - 2), leaving the last element, which is necessarily the largest.

(2) Assuming that it is the i-th order, it can be seen that the first i-1 elements are already ordered. Now look for the i-th element, just start at the end of the array, scan to the ith element, and compare them two by two.

So, you need an inner loop that starts at the end of the array (subscript N - 1) and scans to (subscript i + 1).

Core code

publicvoidbubbleSort(int[]list){

Inttemp = 0; / / temporary number used for exchange

// number of times to traverse

For(inti = 0;i < list.length - 1;i++){

// Compare the size of two adjacent numbers from the back to the front, and after traversing once, put the ith small number in the array at the ith position.

For(intj = list.length - 1;j > i;j--){

/ / Compare adjacent elements, if the previous number is greater than the following number, then exchange

If(list[j - 1] > list[j]){

Temp = list[j - 1];

List[j - 1] = list[j];

List[j] = temp;

}

}

System.out.format("第%d趟: ",i);

printAll(list);

}

}

Bubble sorting algorithm performance

Learn about bubble sorting

time complexity

If the initial state of the file is positive, the scan can be done in one scan. The required number of keyword comparisons C and the number of recording movements M reach a minimum: Cmin = N - 1, Mmin = 0. Therefore, the best time complexity for bubble sorting is O(N).

If the initial file is reversed, an N -1 趟 sort is required. For each sort, a comparison of N - i keywords is performed (1 ≤ i ≤ N - 1), and each comparison must be moved three times to reach the exchange record position. In this case, the number of comparisons and movements reaches a maximum:

Cmax = N(N-1)/2 = O(N2)

Mmax = 3N(N-1)/2 = O(N2)

The worst-case complexity of bubble sorting is O(N2).

Therefore, the average time complexity of bubble sorting is O(N2).

To sum up, it is actually a sentence: when the data is closer to the positive sequence, the bubble sorting performance is better.

Algorithm stability

Bubble sorting is to adjust small elements or to adjust large ones. The comparison is the comparison of two adjacent elements, and the exchange also occurs between these two elements.

So the order of the same elements does not change, so bubble sorting is a stable sorting algorithm.

optimization

A common improvement to bubble sorting is to add the iconic variable exchange, which is used to mark whether there is data exchange in a certain sorting process.

If there is no data exchange when sorting is performed, it means that all the data is in order, and the sorting can be ended immediately, avoiding unnecessary comparison process.

Core code

// Optimization algorithm for bubbleSort

publicvoidbubbleSort_2(int[]list){

Inttemp = 0; / / temporary number used for exchange

booleanbChange = false;// exchange flag

// number of times to traverse

For(inti = 0;i < list.length - 1;i++){

bChange = false;

// Compare the size of two adjacent numbers from the back to the front, and after traversing once, put the ith small number in the array at the ith position.

For(intj = list.length - 1;j > i;j--){

/ / Compare adjacent elements, if the previous number is greater than the following number, then exchange

If(list[j - 1] > list[j]){

Temp = list[j - 1];

List[j - 1] = list[j];

List[j] = temp;

bChange = true;

}

}

// If the flag is false, the current round of traversal is not exchanged, it is already an ordered sequence, and the sort can be ended.

If(false == bChange)

Break;

System.out.format("第%d趟: ",i);

printAll(list);

}

}

Complete reference code

Packagenotes.javase.algorithm.sort;

importjava.util.Random;

publicclassBubbleSort{

publicvoidbubbleSort(int[]list){

Inttemp = 0; / / temporary number used for exchange

// number of times to traverse

For(inti = 0;i < list.length - 1;i++){

// Compare the size of two adjacent numbers from the back to the front, and after traversing once, put the ith small number in the array at the ith position.

For(intj = list.length - 1;j > i;j--){

/ / Compare adjacent elements, if the previous number is greater than the following number, then exchange

If(list[j - 1] > list[j]){

Temp = list[j - 1];

List[j - 1] = list[j];

List[j] = temp;

}

}

System.out.format("第%d趟: ",i);

printAll(list);

}

}

// Optimization algorithm for bubbleSort

publicvoidbubbleSort_2(int[]list){

Inttemp = 0; / / temporary number used for exchange

booleanbChange = false;// exchange flag

// number of times to traverse

For(inti = 0;i < list.length - 1;i++){

bChange = false;

// Compare the size of two adjacent numbers from the back to the front, and after traversing once, put the ith small number in the array at the ith position.

For(intj = list.length - 1;j > i;j--){

/ / Compare adjacent elements, if the previous number is greater than the following number, then exchange

If(list[j - 1] > list[j]){

Temp = list[j - 1];

List[j - 1] = list[j];

List[j] = temp;

bChange = true;

}

}

// If the flag is false, the current round of traversal is not exchanged, it is already an ordered sequence, and the sort can be ended.

If(false == bChange)

Break;

System.out.format("第%d趟: ",i);

printAll(list);

}

}

// print the complete sequence

publicvoidprintAll(int[]list){

For(intvalue : list){

System.out.print(value + " ");

}

System.out.println();

}

Publicstaticvoidmain(String[]args){

// Initialize a random sequence

finalintMAX_SIZE = 10;

Int[]array = newint[MAX_SIZE];

Random random = newRandom();

For(inti = 0;i < MAX_SIZE;i++){

Array[i] = random.nextInt(MAX_SIZE);

}

/ / Call the bubble sorting method

BubbleSort bubble = newBubbleSort();

System.out.print("Pre-sort: ");

bubble.printAll(array);

// bubble.bubbleSort(array);

bubble.bubbleSort_2(array);

System.out.print("After sorting: ");

bubble.printAll(array);

}

}

operation result

Learn about bubble sorting

Toggle Switches

Toggle Switches,Waterproof Toggle Switch,Waterproof Rocker Switch,Mini Toggle Switch

Lishui Trimone Electrical Technology Co., Ltd , https://www.3gracegfci.com