字符串排序————选择排序算法
字符串排序————选择排序算法
我们来处理一个按字母表顺序排序字符串的问题,主要用strcmp()函数来确定两个字符串的顺序,代码如下:
/** @Author: Your name* @Date: 2020-02-24 14:35:13* @Last Modified by: Your name* @Last Modified time: 2020-02-25 15:02:26*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 81
#define LIM 20
#define HALT ""
char *s_gets(char *str,int n);
void stsrt(char *strings[],int n);//传入的是指针数组
int main()
{char input[LIM][SIZE];char *ptstr[LIM];int ct = 0;int k;printf("Input up to %d lines,and i will sort them.\n",LIM);printf("To stop,press the Enter key at a lines start.\n");//s_gets()函数会把换行符转换为空字符while(ct<LIM&&s_gets(input[ct],SIZE)!=NULL&&input[ct][0]!='\0')//所以要额外增加一个开头字符不等于空字符的条件{ptstr[ct] = input[ct];//默认指针变量指向按顺序输入的字符数组ct++;}//当输入的行数满足条件时跳出循环,然后对指针数组进行排序stsrt(ptstr,ct);//排序函数puts("Here are the sorted list:\n");for(k = 0;k<ct;k++){puts(ptstr[k]);//排序后的指针}getchar();getchar();return 0;
}
void stsrt(char *strings[],int n)//传入的是指针数组
{char *temp;int top,seek;for(top = 0;top<n-1;top++)//外层循环控制遍历的总次数{for(seek = top;seek<n;seek++)//假设每次遍历的时候首元素最小,后面的依次与首元素比较{if(strcmp(strings[top],strings[seek])>0)//如果大于0,说明首元素的地址靠后,然后交换地址{temp = strings[top];strings[top] = strings[seek];strings[seek] = temp;}}}
}
char *s_gets(char *str,int n)//处理输入问题
{char *ret;int i = 0;ret = fgets(str,n,stdin);if(ret){while(str[i]!='\n'&&str[i]!='\0'){i++;}if(str[i]=='\n'){str[i]='\0';}else{while(getchar()!='\n'){continue;}} }return ret;
}
下面是程序的输出案例:
Input up to 20 lines,and i will sort them.
To stop,press the Enter key at a lines start.O that T was where I woule be
Then would i be where I am not
But where I am I must be
And where I would be I can notHere are the sorted list:And where I would be I can not
But where I am I must be
Othat T was where I woule be
Then would i be where I am not
排序指针而非排序字符串
该程序的巧妙之处在于排序的是指向字符串的指针,而不是字符串本身。我们来分析一下具体怎么做:
-
最初,ptstr[0]被设置为input[0],ptstr[1]被设置为input[1],以此类推。
这意味着ptstr[i]指向数组input[i]的首字符。
-
每个input[i]都是内含81个元素的数组,每个ptstr[i]都是一个单独的变量。
排序过程把ptstr重新排列,并未改变input.
-
如果按字母顺序input[1]在input[0]前面,程序便交换他们的指针
即ptstr[0]指向input[1]的开始,而ptstr[1]指向input[0]的开始
这样做比用strcpy()交换两个input字符串的内容简单的多,而且还保留了input数组中的原始顺序。
图解如下:
发布评论