@[TOC] 20210228
字符串排序
#include <stdio.h>
#include <string.h>
#define SIZE 81
#define LIM 20
#define HALT ""
void stsrt(char* strings[], int num);
int main(void)
{
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 line's start.\n");
while (ct < LIM && s_gets(input[ct], SIZE) != NULL && input[ct][0] != '\0')
{
ptstr[ct] = input[ct];
ct++;
}
stsrt(ptstr, ct);
puts("\nHere's the sorted list:\n");
for (k = 0; k < ct; k++)
puts(ptstr[k]);
return 0;
}
void stsrt(char* strings[], int num)
{
char* temp;
int top, seek;
for (top = 0; top < num - 1; top++)
for (seek = top + 1; seek < num; seek++)
if (strcmp(strings[top], strings[seek]) > 0)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
}
这里strcmp()函数通过字符串比较,利用其返回值完成排序,排序方法为选择排序算法(selection sort algorithm)。
其中自定义的s_gets()函数, 若输入空行, 则输入的回车被替换为“\0”
input[ct][0] 用于检测空行
排序指针而非字符串
指针ptrst[i] 指向数组input[i]的首字符, 排序过程仅改变了ptrst的排列,input仍保留其原始顺序
选择排序算法
利用两层for循环, 外层确定“首元素”, 内层将首元素与每个元素进行比较, 内层循环结束时, 首元素包含的指针指向机器排序序列最靠前的(人话:最值将会排到第一个/最后一个的位置), 随后外层循环重复该过程, 持续到所有元素排序完毕。