[leetcode]922. 按奇偶排序数组 II

1.题目:
给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

2.代码:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* sortArrayByParityII(int* A, int ASize, int* returnSize) {
    int p1=0,p2=1;
    int temp;
    *returnSize=ASize;
    while(p1<ASize&&p2<ASize){
        while(p1<ASize&&A[p1]%2==0)
            p1+=2;
        while(p2<ASize&&A[p2]%2==1)
            p2+=2;
        if(p1>ASize||p2>ASize)								//[0,1]这种情况。
            return A;       
        temp=A[p1];
        A[p1]=A[p2];
        A[p2]=temp;
        p1+=2;
        p2+=2;
    }    
    return A;
}

3.标题:

快速排序思想。

猜你喜欢

转载自blog.csdn.net/MJ_Lee/article/details/88247484