using System;
namespace TotalSort
{
/**////
/// 全排列的遞歸算法
///
class Class1
{
/**////
/// 應用程序的主入口點。
///
[STAThread]
static void Main(string[] args)
{
//char[] s = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
char[] s = "abcde".ToCharArray();
TotalSort(s, 0);
Console.WriteLine("\n\n總數(shù):{0}", resultCount);
Console.ReadLine();
}
static int resultCount = 0;
public static void TotalSort(char[] list, int start) {
int end = list.Length - 1;
if (start == end) {
resultCount++;
Console.WriteLine(list);
}
else {
for (int i = start; i <= end; i++) {
char[] temp = new char[list.Length];
list.CopyTo(temp, 0);
char tempc = temp[start];
temp[start] = temp[i];
temp[i] = tempc;
TotalSort(temp, start + 1);
}
}
}
}
}
本來想測試 a - z 的全排列,但估算了一下數(shù)目相當驚人,只好作罷。
(這個數(shù)目是 26!)
采用了遞歸僅僅是為了鍛煉算法,效率肯定是很低的。
namespace TotalSort
{
/**////
/// 全排列的遞歸算法
///
class Class1
{
/**////
/// 應用程序的主入口點。
///
[STAThread]
static void Main(string[] args)
{
//char[] s = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
char[] s = "abcde".ToCharArray();
TotalSort(s, 0);
Console.WriteLine("\n\n總數(shù):{0}", resultCount);
Console.ReadLine();
}
static int resultCount = 0;
public static void TotalSort(char[] list, int start) {
int end = list.Length - 1;
if (start == end) {
resultCount++;
Console.WriteLine(list);
}
else {
for (int i = start; i <= end; i++) {
char[] temp = new char[list.Length];
list.CopyTo(temp, 0);
char tempc = temp[start];
temp[start] = temp[i];
temp[i] = tempc;
TotalSort(temp, start + 1);
}
}
}
}
}
本來想測試 a - z 的全排列,但估算了一下數(shù)目相當驚人,只好作罷。
(這個數(shù)目是 26!)
采用了遞歸僅僅是為了鍛煉算法,效率肯定是很低的。