Bubble sort (sorting algorithm)

1. Bubble sorting can sort the messy sequences neatly;

For example, given an array {5, 2, 1, 4, 3, 6, 7, 8, 9, 10} after bubble sorting, it can become

{1,2,3,4,5,6,7,8,9,10};

2. Algorithm principle

Compare adjacent elements, if the first is larger than the second, exchange the two elements, and then compare the larger element with the latter element, similarly, if it is larger than the latter, exchange the two until the largest element is placed In the last position, a bubble sort is completed. If ten data are compared, and the first number needs to be compared with the other nine, it takes nine times. If the second number is compared, it does not need to be compared with that already at the end The maximum number of comparisons is 10-1-1=8, and only eight comparisons are required. One trip of bubble sorting will put the larger numbers behind, and 10 elements require up to nine trips.

3. Code display

int main()
{
	int  arr[10] = {10,9,8,7,6,5,4,3,2,1};
	int sz = sizeof(arr) / sizeof(arr[0]);//数组长度
	int i;
	for (i = 0; i < sz - 1; i++)//趟数
	{
		int j = 0;
		for (j = 0; j < sz - 1 - i; j++)//比较次数
		{
			if (arr[j] > arr[j + 1])//前面大于后面,交换
			{
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
    }
	for (i = 0; i < sz; i++)//打印数组
	{
		printf("%d ", arr[i]);
	}
}

3. Run the display

 

Guess you like

Origin blog.csdn.net/yyqzjw/article/details/131909947