The bubble sort written to my girlfriend is easy to understand with pictures and texts.

I. Introduction

Bubble sort is an exchange sort.

What is a swap sort?

The answer is: compare the keywords to be sorted in pairs, and exchange the pairs that do not meet the order requirements until the entire table meets the order requirements.

2. Algorithmic thinking

It repeatedly walks through the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is, the sequence has been sorted.

The name of this algorithm comes from the fact that the smaller elements will slowly "float" to the top of the sequence through the exchange, hence the name bubble sort.

Schematic diagram of dynamic effect:

Sort(1): Bubble sort

Suppose there is an unordered sequence of size N. Take ascending bubble sort as an example. Bubble sort is to compare adjacent elements pairwise in each sorting process, placing small numbers in the front and large numbers in the back.

1. Code

C++:

#include <iostream>
#include <vector>

using namespace std;

vector<int> bubbleSort(vector<int> list){
	vector<int> result;
	if (list.empty()){
		return result;
	}

	result = list;
	int temp;
	// 要遍历的次数
	for (int i = 0; i < result.size() - 1; ++i){
		cout << "第" << i + 1 << "趟排序:" << endl;;
		// 从后向前依次的比较相邻两个数的大小
		for (int j = 0; j < result.size() - 1; j++){
			// 如果后面的元素小,则交换它们的位置
			if (result[j + 1] < result[j]){
				temp = result[j + 1];
				result[j + 1] = result[j];
				result[j] = temp;
			}
			cout << "排序中:";
			for (int s = 0; s < result.size(); s++){
				cout << result[s] << " ";
			}
			cout << endl;
		}
		cout << "排序结果:";
		for (int s = 0; s < result.size(); s++){
			cout << result[s] << " ";
		}
		cout << endl;
	}
	return result;
}

void main(){
	int arr[] = { 6, 4, 8, 1, 2, 3, 9 };
	vector<int> test(arr, arr + sizeof(arr) / sizeof(arr[0]));
	cout << "排序前" << endl;
	for (int i = 0; i < test.size(); i++){
		cout << test[i] << " ";
	}
	cout << endl;
	vector<int> result;
	result = bubbleSort(test);
	cout << "排序后" << endl;
	for (int i = 0; i < result.size(); i++){
		cout << result[i] << " ";
	}
	cout << endl;
	system("pause");
}

operation result:

Sort(1): Bubble sort

Python:

# -*- coding:utf-8 -*-

def bubbleSort(input_list):
	'''
	函数说明:冒泡排序(升序)
	Author:
		www.cuijiahua.com
	Parameters:
		input_list - 待排序列表
	Returns:
		sorted_list - 升序排序好的列表
	'''
	if len(input_list) == 0:
		return []
	sorted_list = input_list
	for i in range(len(sorted_list) - 1):
		print('第%d趟排序:' % (i + 1))
		for j in range(len(sorted_list) - 1):
			if sorted_list[j + 1] < sorted_list[j]:
				sorted_list[j], sorted_list[j + 1] = sorted_list[j + 1], sorted_list[j]
			print(sorted_list)
	return sorted_list

if __name__ == '__main__':
	input_list = [50, 123, 543, 187, 49, 30, 0, 2, 11, 100]
	print('排序前:', input_list)
	sorted_list = bubbleSort(input_list)
	print('排序后:', sorted_list)

The operation effect is the same as above.

3. Algorithm Analysis

1. The performance of the bubble sort algorithm

Sort(1): Bubble sort

2. Time complexity

If the initial state of the file is in positive order , the sorting can be completed in one scan. The required number of keyword comparisons C and number of record moves M both reach the minimum value: Cmin = N - 1, Mmin = 0. Therefore, the best time complexity of bubble sort is O(N).

However, the above code cannot complete the sorting in one scan, it will perform a full scan. Therefore, an improved method is that when it is found that it is already in positive order during the bubbling, there is no need to continue the comparison. The improvement method will be introduced in a while.

If the original file is in reverse order , N -1 sorting is required. Each sorting requires N - i keyword comparisons (1 ≤ i ≤ N - 1), and each comparison must move the record three times to exchange the record position. In this case, both comparisons and moves are at their maximum:

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

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

The worst time complexity of bubble sort is O(N^2).

Therefore, the average time complexity of bubble sort is O(N^2).

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

3. Algorithm stability

Assuming that there are multiple records with the same keyword in the sequence of records to be sorted, if sorted, the relative order of these records remains unchanged, that is, in the original sequence, r[i]=r[j], and r [i] is before r[j], and in the sorted sequence, r[i] is still before r[j], the sorting algorithm is said to be stable; otherwise, it is said to be unstable.

Bubble sort is to move small elements forward or large elements backward. is a 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 sort is a stable sorting algorithm .

4. Optimization

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

If there is no data exchange during a certain sorting, it means that all the data is in order , and the sorting can be ended immediately to avoid unnecessary comparison process.

1. Code

C++:

#include <iostream>
#include <vector>

using namespace std;

vector<int> bubbleSort(vector<int> list){
	vector<int> result;
	if (list.empty()){
		return result;
	}

	result = list;
	int temp;
	// 要遍历的次数
	for (int i = 0; i < result.size() - 1; ++i){
		cout << "第" << i + 1 << "趟排序:" << endl;;
		//交换标志位
		bool bChanged = false;
		// 从后向前依次的比较相邻两个数的大小
		for (int j = 0; j < result.size() - 1; j++){
			// 如果后面的元素小,则交换它们的位置
			if (result[j + 1] < result[j]){
				temp = result[j + 1];
				result[j + 1] = result[j];
				result[j] = temp;
				bChanged = true;
			}
			cout << "排序中:";
			for (int s = 0; s < result.size(); s++){
				cout << result[s] << " ";
			}
			cout << endl;
		}
		// 如果标志为false,说明本轮遍历没有交换,已经是有序数列,可以结束排序
		if (false == bChanged){
			break;
		}
		cout << "排序结果:";
		for (int s = 0; s < result.size(); s++){
			cout << result[s] << " ";
		}
		cout << endl;
	}

	return result;
}

void main(){
	int arr[] = { 6, 4, 8, 1, 2, 3, 9 };
	vector<int> test(arr, arr + sizeof(arr) / sizeof(arr[0]));
	cout << "排序前" << endl;
	for (int i = 0; i < test.size(); i++){
		cout << test[i] << " ";
	}
	cout << endl;
	vector<int> result;
	result = bubbleSort(test);
	cout << "排序后" << endl;
	for (int i = 0; i < result.size(); i++){
		cout << result[i] << " ";
	}
	cout << endl;
	system("pause");
}

operation result:

Sort(1): Bubble sort

Python:

# -*- coding:utf-8 -*-

def bubbleSort(input_list):
	'''
	函数说明:冒泡排序(升序)
	Author:
		www.cuijiahua.com
	Parameters:
		input_list - 待排序列表
	Returns:
		sorted_list - 升序排序好的列表
	'''
	if len(input_list) == 0:
		return []
	sorted_list = input_list
	for i in range(len(sorted_list) - 1):
		bChanged = False
		print('第%d趟排序:' % (i + 1))
		for j in range(len(sorted_list) - i - 1):
			if sorted_list[j + 1] < sorted_list[j]:
				sorted_list[j], sorted_list[j + 1] = sorted_list[j + 1], sorted_list[j]
				bChanged = True
			print(sorted_list)
		if not bChanged:
			break
	return sorted_list

if __name__ == '__main__':
	input_list = [50, 123, 543, 187, 49, 30, 0, 2, 11, 100]
	print('排序前:', input_list)
	sorted_list = bubbleSort(input_list)
	print('排序后:', sorted_list)

The operation effect is the same as above.

Finally, send you two brushing notes:

It's not easy to be original. If it helps or inspires a little, I hope to give Jack a three-click!

I wish everyone who is doing it is an offe harvester, and the three consecutive super doubles!

 

Guess you like

Origin blog.csdn.net/c406495762/article/details/116904774