写一个函数用起泡法对输人的10个字符按由小到大顺序排列

写一个函数,用“起泡法”对输人的10个字符按由小到大顺序排列

题目解析:

该题主要是对冒泡排序的理解,外层循环控制排序的趟数,内层循环主要是进行每一趟排序的比较,如果前面的字符大于后面的字符,就进行交换,每做一趟排序,就把一个最大字符排在最后,以及每做一趟排序就需要少比较一个字符。

代码示例:

#include<stdio.h>
#include<string.h>

void BubbleSort(char str[])
{
	int i, j;
	char tmp;
	int len = strlen(str);
	for(i=0; i<len-1; ++i)
	{
		for(j=0; j<len-i-1; ++j)
		{
			if(str[j] > str[j+1])
			{
				tmp = str[j];
				str[j] = str[j+1];
				str[j+1] = tmp;
			}
		}
	}
}

int main()
{
	int i;
	char str[11] = {0};
	printf("请输入10个字符:>");
	for(i=0; i<10; ++i)
		scanf("%c", &str[i]);

	BubbleSort(str);

	printf("string sorted: %s
", str);
	return 0;
}

运行结果:

写一个函数,用起泡法对输人的10个字符按由小到大顺序排列

原文地址:https://www.cnblogs.com/inta/p/13361451.html