将数组按照奇偶顺序排列

  给定一个数列A,试将其变为奇数在左偶数在右的形式。例如A=[12,8,7,5,6,11],则变换后的A'=[11,5,7,8,6,12].只需要先奇数后偶数即可,不需要排序。

  标准的快速排序的思想,设置两个下标low和high,初始时,low=0,high = length - 1, 将temp =
data[low]暂存第一个数,此时data[low](即data[0])已经保存便可以被覆盖。按照快速排序的思想,从high开始往左扫描,high每次减1,直到碰到第一个奇数,将这个奇数保存在data[low];同理,从low开始往右扫描,low每次加1,直到碰到第一个偶数,将这个偶数保存在data[high]中,这样下去,最终一定会有low==high,即到达了奇数与偶数的边界处,这时data[low]=temp;将原来暂存的数放到中间位置。这样不需要来回交换。

  上代码。

#include <stdio.h>
#define MAXLENGTH 200

void printArray(int * data,int length){//输出函数
    for(int i=0;i<length;i++)
        printf("%d  ",data[i]);
    printf("\n");
}

int main(){
    int data[MAXLENGTH];
    int arrayLength=0;//数组长度
    printf("please input the lenght of the array!\n");
    scanf("%d",&arrayLength);


    for(int i=0;i<arrayLength;i++)//读入数组
            scanf("%d",&data[i]);

    int low = 0;
    int high = arrayLength  - 1;
    int temp = data[low];
    while(high > low){
        while(data[high]%2 == 0 && high > low)//从high处往左边找到第一个奇数
            high--;
        data[low] = data[high];
        
        while(data[low]%2 != 0 && high > low)//从low处往右边找到第一个偶数
            low++;
        data[high]=data[low];
        printArray(data,arrayLength);
    }
    data[high] = temp;//将暂存的第一个数保存在最中间

    printArray(data,arrayLength);
    return 0;
}

 

posted @ 2013-02-27 19:12  CodeMeals  阅读(721)  评论(0编辑  收藏  举报
reliable statistics
Visitors