冒泡排序也可以使用在字符的排序中
写一个函数实现将任意字符串按照ASCII值从小到大顺序排列
函数原型为:
char *sort(char *s);
#include <stdio.h>
#include <string.h>
#define LENGTH 20
char *sort(char *s)
{
char tmpc; //定义一个字符型的临时存放变量
int len,i,j; //定义三个整型用来存放字符串长度,和循环控制变量
len=strlen(s);
for(i=0;i < len-1;i++) //从前往后依次置换出最小的元素
{
for (j=i+1;j<len;j++)
{
if (s[i] > s[j])
{
tmpc=s[i];
s[i]=s[j];
s[j]=tmpc; //冒泡排序
}
}
}
return s;
}
void main()
{
char str[LENGTH];
printf("please input a string (less then %d length):\n",LENGTH);
scanf("%s",str);
printf("the string is : %s\n",str);
printf("the sorted string is : %s\n",sort(str));
}
使用冒泡排序的思想对字符数组中的值进行排序
原文地址http://soft.dog/2016/11/24/c-basic-14/
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。