Ste*_*fan 6 arrays algorithm permutation
请考虑以下情形.
我有一系列数字:
[ 1,2,3,4 ]
Run Code Online (Sandbox Code Playgroud)
如果加入这个数组,我的数字是1234.
我想交换数字来实现最接近的数字.
1234将成为1243,这将成为1324,这将成为1342等等.
我需要使用什么算法在数组中进行此更改?
理想情况下,我想以这种方式使用该算法:(假设Array将此算法作为一个称为演练的函数)
[ 1,2,3,4].walkthrough() # gives [ 1, 2, 4, 3 ]
[ 1,2,4,3].walkthrough() # gives [ 1, 3, 2, 4 ]
Run Code Online (Sandbox Code Playgroud)
数字列表继续:
1234
1243
1324
1342
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
这给你下一个排列:
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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
将Array.Sort更改为Array.Reverse.这些项目始终按降序排列,并且应按升序排列,因此它们会给出相同的结果.