jobdu1516:調整數組順序使奇數位於偶數前面

輸入: ios

每一個輸入文件包含一組測試案例。
對於每一個測試案例,第一行輸入一個n,表明該數組中數字的個數。
接下來的一行輸入n個整數。表明數組中的n個數。 數組

輸出:

對應每一個測試案例,
輸入一行n個數字,表明調整後的數組。注意,數字和數字之間用一個空格隔開,最後一個數字後面沒有空格。 測試

樣例輸入:
5
1 2 3 4 5
樣例輸出:
1 3 5 2 4
個人思路:設定兩個數組odds和evens,分別用於存放奇數和偶數。在輸出時,分別打印兩個數組中的內容就好了。

#include <iostream>
using namespace std;

int main() {
	int n;
	while(cin>>n){
		int odds[n];
		int evens[n];
		int a;
		int o_index = 0;
		int e_index = 0;
		for(int i=0;i<n;i++){

			cin>>a;
			if((a & 1) == 1){
				odds[o_index++] = a;
			}else{
				evens[e_index++] = a;
			}

		}

		//輸出
		for(int i=0;i<o_index;i++){
			cout<<odds[i]<<" ";
		}
		for(int i=0;i<e_index-1;i++){
			cout<<evens[i]<<" ";
		}

		cout<<evens[e_index-1]<<endl;


	}
	return 0;
}
相關文章
相關標籤/搜索