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