/**
* 实验题目:
* 实现可变长度的字符串序列快速排序算法
* 实验目的:
* 掌握快速排序算法及其应用
* 实验内容:
* 某个待排序的序列是一个可变长度的字符串序列,这些字符串
* 一个接一个地存储于单个字符数组中。采用快速排序方法对这个字
* 符串序列进行排序。
*/
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100 // 最大的字符串长度
typedef struct node
{
int start; // 该字符串在s中的起始位置
int length; // 该字符串的长度
}rec_type; // 指示字符串位置的记录类型
/*-----------------比较s1位置指示的字符串和tmp指示的字符串的大小------------------*/
static int string_comp(char s[], rec_type recs[], int s1, rec_type tmp)
{
char str1[MAX_LEN], str2[MAX_LEN];
int i, j;
for(j = 0, i = recs[s1].start; i < recs[s1].start + recs[s1].length; i++, j++)
str1[j] = s[i];
str1[j] = '\0';
for(j = 0, i = tmp.start; i < tmp.start + tmp.length; i++, j++)
str2[j] = s[i];
str2[j] = '\0';
return strcmp(str1, str2);
}
/*-----------------实现快速排序----------------*/
static void quick_sort(char s[], rec_type recs[], int low, int high)
{
int i, j;
rec_type tmp;
i = low;
j = high;
if(low < high)
{
tmp = recs[low];
while(i != j)
{
while(j > i && string_comp(s, recs, j, tmp) > 0)
j--;
recs[i] = recs[j];
while(j > i && string_comp(s, recs, i, tmp) < 0)
i++;
recs[j] = recs[i];
}
recs[i] = tmp;
quick_sort(s, recs, low, i - 1);
quick_sort(s, recs, i + 1, high);
}
}
int main(void)
{
int i, j;
int n = 6;
char s[] = {"whileifif-elsedo-whileforcase"};
// 定义结构体数组并初始化
rec_type recs[] = {
{0, 5}, {5, 2}, {7, 7}, {14, 8}, {22, 3}, {25, 4}
};
printf("排序前的字符串:\n");
for(i = 0; i < n; i++)
{
printf(" ");
for(j = recs[i].start; j < recs[i].start + recs[i].length; j++)
printf("%c", s[j]);
printf("\n");
}
quick_sort(s, recs, 0, n - 1);
printf("排序后的字符串:\n");
for(i = 0; i < n; i++)
{
printf(" ");
for(j = recs[i].start; j < recs[i].start + recs[i].length; j++)
printf("%c", s[j]);
printf("\n");
}
return 0;
}
测试结果:
排序前的字符串:
while
if
if-else
do-while
for
case
排序后的字符串:
case
do-while
for
if
if-else
while