输出一个任意数组的全排列
这是一个控制台应用程序,用于体系算法思想。
代码如下:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.Write("请输入数字长度:"); 6 int n = Convert.ToInt32(Console.ReadLine()); 7 int[] A1 = new int[n]; 8 for (int i = 0; i < n; i++) 9 { 10 Console.Write($"请输入第{i + 1}个数:"); 11 A1[i] = Convert.ToInt32(Console.ReadLine()); 12 } 13 Console.WriteLine("结果:"); 14 PrintFullPermutation(A1); 15 Console.ReadKey(); 16 } 17 18 19 /// <summary> 20 /// 输出一个数组的全排列 21 /// </summary> 22 /// <param name="array"></param> 23 private static void PrintFullPermutation(int[] array) 24 { 25 //0.合法性校验 26 if (array == null || array.Length == 0) 27 { 28 return; 29 } 30 //1.复制一个新数组:修改时在临时数组中修改 31 int[] temp = new int[array.Length]; 32 for (int i = 0; i < array.Length; i++) 33 { 34 temp[i] = array[i]; 35 } 36 //2.将新数组升序排列 37 int itemp; 38 for (int i = 0; i < temp.Length; i++) 39 { 40 for (int j = i; j < temp.Length; j++) 41 { 42 itemp = array[i]; 43 array[i] = array[j]; 44 array[j] = itemp; 45 } 46 } 47 //3.依次寻找并打印全排序 48 PrintArray(temp); 49 while (!isDesc(temp)) 50 { 51 FindNextArray(temp); 52 PrintArray(temp); 53 } 54 } 55 /// <summary> 56 /// 打印数组 57 /// </summary> 58 /// <param name="array">数组</param> 59 private static void PrintArray(int[] array) 60 { 61 for (int i = 0; i < array.Length; i++) 62 { 63 Console.Write(array[i].ToString() + '\t'); 64 } 65 Console.WriteLine(); 66 } 67 /// <summary> 68 /// 判断一个数组内元素是否降序排列 69 /// </summary> 70 /// <param name="array">数组</param> 71 /// <returns></returns> 72 private static bool isDesc(int[] array) 73 { 74 int temp = array[0]; 75 for (int i = 1; i < array.Length; i++) 76 { 77 if (array[i] > array[i - 1]) 78 { 79 return false; 80 } 81 } 82 return true; 83 } 84 /// <summary> 85 /// 找到下一组排列 86 /// </summary> 87 /// <param name="array"></param> 88 private static void FindNextArray(int[] array) 89 { 90 //1.找出数组的最大值 91 int max = array[0]; 92 for (int i = 1; i < array.Length; i++) 93 { 94 if (max < array[i]) 95 { 96 max = array[i]; 97 } 98 } 99 //2.从后向前找:找到第一组后数大于前数,以后数位置为signer 100 int signer = array.Length - 1; 101 for (int i = array.Length - 1; i > 0; i--) 102 { 103 if (array[i] > array[i - 1]) 104 { 105 signer = i; 106 break; 107 } 108 } 109 //3.从signer向后找:找到大于且最接近于array[signer-1]的数array[t] 110 int t = signer; 111 for (int i = signer; i < array.Length; i++) 112 { 113 if (array[i] > array[signer - 1] && array[i] < max) 114 { 115 t = i; 116 max = array[t]; 117 } 118 } 119 //4.将找到的array[t]和array[signer-1]互换 120 int temp = array[t]; 121 array[t] = array[signer - 1]; 122 array[signer - 1] = temp; 123 //5.为signer之后的元素升序排序 124 for (int i = signer; i < array.Length; i++) 125 { 126 for (int j = i + 1; j < array.Length; j++) 127 { 128 if (array[i] > array[j]) 129 { 130 temp = array[i]; 131 array[i] = array[j]; 132 array[j] = temp; 133 } 134 } 135 } 136 } 137 }