Algorithm 数组元素排列算法
考虑以下场景 我有一组数字:Algorithm 数组元素排列算法,algorithm,arrays,permutation,Algorithm,Arrays,Permutation,考虑以下场景 我有一组数字: [ 1,2,3,4 ] 如果加入此数组,我将拥有编号1234 我想交换数字,以获得更高的数字 1234将变成1243,这将变成1324,这将变成1342,以此类推 我需要使用什么算法在数组中进行此更改? 理想情况下,我希望以这种方式使用算法: (假设数组将此算法作为一个称为漫游的函数) 数字清单如下: 1234 1243 1324 1342 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241这看起来像是要按词汇顺
[ 1,2,3,4 ]
如果加入此数组,我将拥有编号1234
我想交换数字,以获得更高的数字
1234将变成1243,这将变成1324,这将变成1342,以此类推
我需要使用什么算法在数组中进行此更改?
理想情况下,我希望以这种方式使用算法:
(假设数组将此算法作为一个称为漫游的函数)
数字清单如下: 1234
1243
1324
1342
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241这看起来像是要按词汇顺序生成列表的排列。这些搜索词应该会让你走上一条有用的道路
例如,Python在2.6版之后的模块中包含了这一点。该文档显示了实现这种算法的代码。这将为您提供下一个排列:
bool Increase(int[] values) {
// locate the last item which is smaller than the following item
int pos = values.Length - 2;
while (pos >= 0 && values[pos] > values[pos + 1]) pos--;
// if not found we are done
if (pos == -1) return false;
// locate the item next higher in value
int pos2 = values.Length - 1;
while (values[pos2] < values[pos]) pos2--;
// put the higher value in that position
int temp = values[pos];
values[pos] = values[pos2];
values[pos2] = temp;
// reverse the values to the right
Array.Reverse(values, pos + 1, values.Length - pos - 1);
return true;
}
bool增加(int[]值){
//找到最后一个小于以下项目的项目
int pos=值。长度-2;
而(pos>=0&&values[pos]>values[pos+1])pos--;
//如果没有找到,我们就完了
如果(pos==-1)返回false;
//找到价值更高的项目
int pos2=值。长度-1;
while(values[pos2]
编辑:已更改数组。排序为Array.Reverse。项目总是按降序排列,并且应该按升序排列,因此它们给出相同的结果。请继续数字行。1342年以后我想1432年来了,然后呢?4132然后4312然后4321?我想你的列表中有一个错误,2413不应该跟着2341吗?是的。。。thanx。。。它已经被修复了您是否有一个与该数组等效的Ruby。排序部分?@Stefan:我从未使用过Ruby,所以没有。数组的这个重载。排序方法对数组的部分进行排序,从第二个参数的索引开始,从第三个参数的长度开始。@paracycle:谢谢。是的,是C。我刚刚发明了它,或者可能重新发明了它……:)仔细想想,排序数组部分的另一种方法是简单地将其反转。项目将始终按降序排列,之后应按升序排列。
bool Increase(int[] values) {
// locate the last item which is smaller than the following item
int pos = values.Length - 2;
while (pos >= 0 && values[pos] > values[pos + 1]) pos--;
// if not found we are done
if (pos == -1) return false;
// locate the item next higher in value
int pos2 = values.Length - 1;
while (values[pos2] < values[pos]) pos2--;
// put the higher value in that position
int temp = values[pos];
values[pos] = values[pos2];
values[pos2] = temp;
// reverse the values to the right
Array.Reverse(values, pos + 1, values.Length - pos - 1);
return true;
}