Implement a bubble sort for an integer array (bubble sort)

Table of contents

The principle of bubble sort method:

Code:

operation result:

Code analysis:

Function implementation code:

operation result:



The principle of bubble sort method :

Repeatedly visit the column of elements to be sorted, compare two adjacent elements in turn, and exchange them if the order (such as from large to small) is wrong. The work of visiting elements is repeated until no adjacent elements need to be exchanged , which means that the element column has been sorted.

For example {2, 1, 4, 5, 7, 3, 6}

After the first visit, becomes {1, 2, 4, 5, 3, 6, 7}

After the second pass, it becomes {1, 2, 4, 5, 3, 6, 7}

After the third time, it becomes {1, 2, 4, 3, 5, 6, 7}

........

After 6 times, sorting is complete

Code:

#include <stdio.h>

int main()
{
	int arr[10] = { 1,3,5,7,9,2,4,6,8,10 };

	int sz = sizeof(arr) / sizeof(arr[0]);
	int k = 0;

	for (k = 0; k < sz - 1; ++k)
	{
		int i = 0;
		for (i = 0; i < sz-1; ++i)
		{
			if (arr[i] > arr[i + 1])
			{
				int temp = arr[i + 1];
				arr[i + 1] = arr[i];
				arr[i] = temp;
			}
		}
	}

	int j = 0;

	for (j = 0; j < sz; ++j)
	{
		printf("%d ", arr[j]);
	}

	return 0;
}

operation result:

Code analysis:

#include <stdio.h>

int main()
{
	int arr[10] = {1,3,5,7,9,2,4,6,8,10};    //创建一个整形数组

	int sz = sizeof(arr) / sizeof(arr[0]);    //计算数组的大小

	int k = 0;    //用k变量来控制所需走访的次数

	for (k = 0; k < sz-1; ++k)//    走访次数应为数组元素个数减一
	{
		int i = 0;//    i变量来控制数组内部不符合顺序元素的交换
		for (i = 0; i < sz-1; ++i)
		{
			if (arr[i] > arr[i + 1])
			{
				int temp = arr[i + 1];   //用temp来当中间变量来交换相邻两个元素
				arr[i + 1] = arr[i];
				arr[i] = temp;
			}
		}
	}
	int j = 0;
	for (j = 0; j < sz; ++j)   //输出打印该数组
	{
		printf("%d ", arr[j]);
	}
	return 0;
}

Function implementation code:

void boild(int arr[10], int sz)
{
	int k = 0;

	for (k = 0; k < sz - 1; ++k)
	{
		int i = 0;

		for (i = 0; i < sz - 1; ++i)
		{
			if (arr[i] > arr[i + 1])
			{
				int temp = arr[i + 1];

				arr[i + 1] = arr[i];

				arr[i] = temp;
			}
		}
	}
}
#include <stdio.h>

int main()
{
	int arr[10] = {1,3,5,7,9,2,4,6,8,11};

	int sz = sizeof(arr) / sizeof(arr[0]);

	boild(arr, sz);

	int j = 0;

	for (j = 0; j < sz; ++j)
	{
		printf("%d ", arr[j]);
	}

	return 0;
}

operation result:

Guess you like

Origin blog.csdn.net/2301_77509762/article/details/130533614