是否可以使用这组非常有限的运算符对整数进行排序?

Is it possible to sort integers with this very limited set of operators?

背景

我正在使用一种非常有限的工具集使用一种奇怪的编程语言。

我想对一个整数列表进行排序,但我无法找出适用于给定工具的算法。不知道有没有可能。

运算符

这是记录可用运算符的一些 JavaScript 代码。

// 1. you can create new variables
// javascript quirk: in order to pass-by-reference, you must store an integer in an object
const v = (value) => {
    return { value: value };
}

// 2. you can set A to B, if B is larger than A
const max = (a,b) => {
    if(b.value > a.value)
        a.value = b.value;
};

// 3. you can set A to B, if B is less than A
const min = (a,b) => {
    if(b.value < a.value)
        a.value = b.value;        
};

// 4. you can swap the values of A and B
const swap = (a,b) => {
    let t = a.value;
    a.value = b.value;
    b.value = t;
};

// 5. you can set A to B
const set = (a,b) => {
    a.value = b.value;
};

// 6. you can add B to A
const add = (a,b) => {
    a.value = a.value + b.value;
};

// 7. you can subtract B from A
const subtract = (a,b) => {
    a.value = a.value - b.value;
};

// 8. you can multiply A by B
const multiply = (a,b) => {
    a.value = a.value * b.value;
};

// 9. you can divide A by B, losing the remainder
// if B == 0, then A is not modified
const divide = (a,b) => {
    if (b.value == 0) return;
    a.value = Math.floor(a.value/b.value);
};

// 10. you can set A to the remainder of A divided by B
// if B == 0, then A is not modified
const mod = (a,b) => {
    if (b.value == 0) return;
    a.value = a.value % b.value;
};

// 11. you can test if A falls within a range of integers, and if true, call a function 
// (see next section for function rules). You cannot do anything with a false
//
// min and max must be hard coded integers (i.e. you cannot pass in variables)
const in_range = (a,min,max) => {
    return (a >= min && a <= max);
};

// 12. you can add an integer to A
// x must be a hard-coded integer, you cannot pass in variables
const add2 = (a,x) => {
    a.value = a.value + x;
};

// 13. you can set A to an integer
// x must be a hard-coded integer, you cannot pass in variables
const set2 = (a,x) => {
    a.value = x;
};

输入

    var a = v(2);
    var b = v(1);
    var c = v(3);

    // you may create as many extra variables as you want
    var temp = v(0);

想要的结果

    a.value == 1
    b.value == 2
    c.value == 3

问题

仅使用上面列出的操作,就可以对整数进行排序?

语言非常有限:

没有循环,或其他 comparison/logic 流可用。

没有数组。

你可以写函数,但是必须遵守上面的规则。您不能将变量传递给函数,它们必须从全局范围访问。

现在 maxmin 的定义已经固定,您可以这样做:

var sum = v(0);
add(sum ,a);
add(sum ,b);
add(sum ,c);

//remember a and set a to min
var olda = v(0);
set(olda,a);
min(a,b);
min(a,c);

//set c to max
max(c,olda);
max(c,b);

//calculate b
set(b,sum);
subtract(b,a);
subtract(b,c);

您可以执行的操作比您需要的多得多。显然,只对 2 个变量进行排序比这更容易,如果你可以对 2 个变量进行排序,那么你可以使用 sorting network.

对任意数量的变量进行排序