字符串排序 ststr函数,采用选择排序方法
(两个for)将每个元素与首元素比较,如待比较元素在前,交换两者
/* 字符串排序功能说明 */
#include<stdio.h>
#include<string.h>
#define SIZE 18
#define LIM 20
void ststr (char *strs[] , int);
char * s_get(char *, int);
int main(void)
{
char input[LIM][SIZE];
char * ptstr[LIM];
int ct = 0;
int k;
while(ct < LIM && s_get(input[ct],SIZE) != NULL && input[ct][0] != '\0')// 新一行直接按Enter,就会提前结束循环
{
ptstr[ct] = input[ct];
ct++;
}
ststr(ptstr, ct);
puts("\n LIST IS: \n");
for(k = 0; k < ct; k++)
puts(ptstr[k]);
return 0;
}
void ststr(char * ptstr[], int ct)
{
char * temp;
int top, seek;
for(top = 0; top < ct - 1; top++)// 遍历循环要用两个for循环
for(seek = top + 1; seek < ct; seek++)
if(strcmp(ptstr[top], ptstr[seek]) > 0)
{
temp = ptstr[top];
ptstr [top] = ptstr[seek];
ptstr [seek] = temp;
}
}
char * s_get(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
//printf(("%c \n", ret_val));
if(ret_val)
{
while(st[i] != '\n' && st[i] != '\0')
i++;
if(st[i] == '\n')
st[i] = '\0';
else
while(getchar() != '\n')
continue;
}
return ret_val;
}