上一组排列与下一组排列

#include 

void swap(int* p, int* q) {
    int t = *p;
    *p = *q;
    *q = t;
    return;
}

void reverse(int* p, int l, int r) {
    while (l < r - 1) {
        swap(&p[l], &p[r - 1]);
        l++, r--;
    }
    return;
}

void next_result(int* p, int n) {
    int pos = n - 1;
    while (pos > 0 && p[pos - 1] > p[pos]) pos--;
    if (pos == 0) {
        reverse(p, 0, n);
        return;
    }
    int cnt = 0;
    for (int i = n - 1; i >= pos; i--) {
        if (p[i] > p[pos - 1]) {
            cnt = i;
            break;
        }
    }
    swap(&p[pos - 1], &p[cnt]);
    reverse(p, pos, n);
    return;
}

void prev_result(int* p, int n) {
    int pos = n - 1;
    while (pos > 0 && p[pos] > p[pos - 1]) pos--;
    if (pos == 0) {
        reverse(p, 0, n);
        return;
    }
    reverse(p, pos, n);
    int cnt;
    for (int i = pos; i < n; i++) {
        if (p[i] < p[pos - 1]) {
            cnt = i;
        }
    }
    swap(&p[pos - 1], &p[cnt]);
    return;
}

int main() {
    
    return 0;
}

你可能感兴趣的:(数据结构与算法,算法,数据结构)