实现可变长度的字符串序列快速排序算法

/**
*    实验题目:
*        实现可变长度的字符串序列快速排序算法
*    实验目的:
*        掌握快速排序算法及其应用
*    实验内容:
*        某个待排序的序列是一个可变长度的字符串序列,这些字符串
*    一个接一个地存储于单个字符数组中。采用快速排序方法对这个字
*    符串序列进行排序。
*/

#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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值