C language bubble sort, from small to large, from large to small

Compare adjacent elements. If the first one is bigger than the second one, swap them both.

Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. After this step is completed, the final element will be the largest number.

Repeat the above steps for all elements except the last one.

Keep repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers left to compare.

Sort from smallest to largest. 

#include<stdio.h>
int main()
{
	int arr[10] = {12,4,6,3,78,2,7,9,96,5};
	for (int i = 0; i < 10-1; i++)//控制行,行运行一次必提取一个最大值
	{
		for (int j = 0; j < 10-1-i; j++)//控制列
		{
			if (arr[j] > arr[j + 1]) {
				int temp = arr[j];//定义第三变量,当后面的值大于前面的值进行互换
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
		

	}
	for (int i = 0; i < 10; i++)//遍历
	{
		printf("%d\t", arr[i]);

	}
	return 0;
}

Sort from largest to smallest.

#include<stdio.h>
int main()
{
	int arr[10] = {12,4,6,3,78,2,7,9,96,5};
	for (int i = 0; i < 10-1; i++)//控制行,行运行一次必提取一个最小值
	{
		for (int j = 0; j < 10-1-i; j++)//控制列
		{
			if (arr[j] < arr[j + 1]) {
				int temp = arr[j];//定义第三变量,当后面的值小于前面的值进行互换
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
		

	}
	for (int i = 0; i < 10; i++)//遍历
	{
		printf("%d\t", arr[i]);

	}
	return 0;
}

 

Guess you like

Origin blog.csdn.net/m0_62247560/article/details/124991623