將數組按照奇偶順序排列

來源:互聯網
上載者:User

  給定一個數列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 200void 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;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.