【问题标题】:permutations of a string algorithm analysis字符串算法分析的排列
【发布时间】:2016-06-09 16:10:12
【问题描述】:

我有两种打印字符串排列的算法

这是第一个。

#include<iostream>

int fact(int f)
{
   if(f == 0)
      return 1;
  return f*fact(f-1);
}
int main()
{   
   char A[] = "abc";
   int size = strlen(A);
   int per = fact(size);  // per is the number of permutations we will get

   int j = 0;   // j is the index of the elements of A we will swap

   // this is the algorithm
   for(int i=1;i<=per;i++)
   {   
      cout << A << endl;
      if(j == size-1)
         j = 0;
      swap(A[j],A[j+1]);
      j++;
   }

    return 0;
}

这是第二个。

// C program to print all permutations of the input string

#include <stdio.h>
#include <string.h>

// Function to swap values at two pointers 
void swap(char *x, char *y)
{    
   char temp = *x;
   *x = *y;
   *y = temp;
}

// Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string or sub-string
3. Ending index of the string 

void permute(char *a, int l, int r)
{
  int i;
  if (l == r)
     printf("%s\n", a);
  else
  {
     for(i = l; i <= r; i++)
     {  
        swap((a+l), (a+i));
        permute(a, l+1, r);
        swap((a+l), (a+i)); //backtrack to retain the original string
     }
  }
}

int main()
{
  char str[50];

  gets_s(str);

  int n = strlen(str);
  permute(str, 0, n-1);

  return 0;
}

据我说...两者都应该执行相同的操作...实际上它们确实可以...但仅适用于小输入...例如:“abc”,“abcd”。但是当字符串变大时..例如: "abcdefghi"..第一个比第二个要花很多时间。

我很难分析为什么第二个比第一个表现更好。有人可以向我解释一下吗?

【问题讨论】:

  • 我认为事实函数是罪魁祸首。您是否尝试计算大于 10 的数的阶乘? 15? 20?
  • 让你的事实函数使用循环而不是递归并再次检查。如果它更快,那就是你的问题。
  • 您使用哪种语言?请比较喜欢和喜欢。
  • 我使用 c 和 c++
  • 我不认为事实是一个问题,因为我首先计算阶乘....然后才开始打印...如果您尝试运行打印将花费很多时间代码

标签: c++ string algorithm permutation


【解决方案1】:

在开始打印之前,只需在主函数中添加以下语句:

std::cout.sync_with_stdio(false);

这会为每个 IO 操作禁用与标准 C-streams 的同步。

阅读更多关于它的信息here

【讨论】:

  • @user5422891 “不工作”是指您的 C 程序优于 C++ 代码吗?我能够重现它,添加它之后,C++ 代码比 C 版本运行得更快。我用linux的time命令来测量总时间。
  • 是的……C 的性能仍然优于 C++ 的……当我输入“abcdefghi”时,C++ 似乎根本没有完成……C 的在 15 秒内完成…… ..我没有测量时间...只是一个近似值
  • 我在 C++ 代码中使用 printf 而不是 cout....现在 C 和 C++ 同时完成....输入“abcdefghi”需要 20 秒。是 printf比 cout 更有效率??如果是的话……为什么会这样??
  • @user5422891 你使用哪个编译器?哪个平台?尽管我同意 C++ 流的设计有些糟糕,但不应该比 C printf 慢。几乎总是禁用sync_with_stdio 可以解决这种性能问题。你也可以更新你的 C++ 代码吗?
  • 我在 Windows 10 上使用 Visual Studio 2015 社区
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 2016-05-29
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多