Generate permutations

by podlipensky

JavaScript

function swap(a, i, j) {
    var t = a[i];
    a[i] = a[j];
    a[j] = t;
}

function reverse(a, i, j) {
    while (i < j) {
        swap(a, i, j);
        i++;
        j--;
    }
}

// generates next lexicographic permutation of an array
function nextPerm(a) {
    var i = 0,
        len = a.length;

    while (i < len - 1 && a[i] < a[i+1]) {
        i++;
    }
    var k = i - 1;
    if (k < 0) {
        return a; // this is the last lexicographic permutation
    }
    
    var l = k + 1;
    while (l < len && a[l] > a[k]) {
        l++;
    }
    l--;
    swap(a, l, k);
    
    reverse(a, k + 1, len - 1);
}

var a = [1, 2, 3, 4];

nextPerm(a);

console.log(a);

nextPerm(a);

console.log(a);