c_cpp 给定一组正负整数,重新排列它,使得一端为正整数,另一端为负整数。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 给定一组正负整数,重新排列它,使得一端为正整数,另一端为负整数。相关的知识,希望对你有一定的参考价值。

// without keep the order
void rearrange(int A[], int N) {
    int low = 0, high = N-1;
    while(low < high) {
        while(low < N && A[low] < 0) low++;
        if(low == N) return;
        while(high >= 0 && A[high] > 0) high--;
        if(high < 0) return;
        swap(A[low], A[high]);
        low++;
        high--;
    }
}

// keep the order
void rearrange(int A[], int N) {
    int *B = new int[N];
    int j=0;
    for(int i=0; i<N; i++)
        if(A[i] < 0) B[j++] = A[i];
    for(int i=0; i<N; i++)
        if(A[i] > 0) B[j++] = A[i];
    for(int i=0; i<N; i++)
        A[i] = B[i];
    delete [] B;
}

以上是关于c_cpp 给定一组正负整数,重新排列它,使得一端为正整数,另一端为负整数。的主要内容,如果未能解决你的问题,请参考以下文章