C语言利用指针排序与选择排序算法

 //读入字符串,并排序字符串
#include <stdio.h>
#include <string.h>
#define SIZE 81
#define LIM 20
#define HALT "" void stsrt(char * strings [], int num); //字符串排序函数
char * s_gets(char * st,int n); int main(void)
{
char input[LIM][SIZE];
char *ptstr[LIM];
int ct =;
int k; printf("Input up to %d lines,and I will sort them.\n",LIM);
printf("To stop,press the Enter key at a line's start.\n"); while(ct<LIM && s_gets(input[ct],SIZE)!= NULL && input[ct][]!='\0')
{
ptstr[ct] = input[ct]; //设置指针指向字符串
ct++;
}
stsrt(ptstr,ct); //字符串排序函数
puts("\nHere's the sorted list:\n");
for (k=;k<ct;k++)
puts(ptstr[k]);
return ;
} void stsrt(char *strings [], int num)
{
char *temp;
int top,seek; for(top=;top <num -;top++)
for(seek=top+;seek<num;seek++)
if(strcmp(strings[top],strings[seek])>)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
} char * s_gets(char * st, int n)
{
char * ret_val;
int i=; ret_val = fgets(st, n, stdin); //读取成功,返回一个指针,指向输入字符串的首字符;
if(ret_val)
{
while(st[i]!='\n' && st[i]!='\0')
i++;
if(st[i] =='\n') //fgets会把换行符也吃进来了,fgets会在末尾自动加上\0;
st[i]='\0';
else //其实是'\0'
while(getchar() != '\n') //会把缓冲区后续的字符都清空
continue;
}
return ret_val;
}

程序解读:

这个程序的好处是利用字符串指针数组ptstr进行排序,并未改变input,这样也保留了input数组中的原始顺序。这样的做法比直接用strcpy()交换两个input字符串要简单得多。

程序中还出现了,选择排序算法:(selection sort algorithm):其实就是以strcmp函数为基础来冒泡排序指针

C库中有更高级的排序函数:qsort(),该函数使用一个指向函数的指针进行排序比较。

上一篇:2.深入学习Servlet


下一篇:JavaScript 数据结构与算法之美 - 非线性表中的树、堆是干嘛用的 ?其数据结构是怎样的 ?